Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class A {
    public String f() { return "A"; }
}
public class B extends A {
    public String f() { return "B"; }
    public String g() { return "g"; }
}
A x = new B();
System.out.println(x.g());

What happens?

  • A

    Compile-time error: g not in A

    check_circle
  • B

    Prints g

  • C

    Runtime error

  • D

    Prints null

Explanation

Method calls are checked against the declared type. A has no <code>g()</code>, so this fails to compile.

Want 10 more like this — adaptive to your weak spots?

Related questions