Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class A {}
public class B extends A {
    public void greet() { System.out.print("hi"); }
}
// Usage:
A obj = new A();
if (obj instanceof B) {
    ((B) obj).greet();
} else {
    System.out.print("not B");
}

What is printed?

  • A

    not B

    check_circle
  • B

    ClassCastException

  • C

    hi

  • D

    Compile error

Explanation

obj is a plain A, not a B, so instanceof B is false. The else branch prints "not B".

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

Related questions

AP Computer Science A · Creating References Using Inheritance Hierarchies Practice Question | Acemy