Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class A {
    public String tag() { return "A"; }
}
public class B extends A {
    public String tag() { return "B"; }
    public String extra() { return "extra"; }
}
// Usage:
A obj = new B();
System.out.print(obj.extra());

What occurs?

  • A

    Prints 'B'

  • B

    Prints 'extra'

  • C

    Runtime error

  • D

    Compile error: A has no extra() method

    check_circle

Explanation

Methods callable on obj are limited to those declared in A (the static type). extra() exists only in B, so the compiler reports an error.

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

Related questions