Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class Animal {}
public class Dog extends Animal {
    public void bark() { System.out.print("Woof"); }
}
Animal a = new Animal();
if (a instanceof Dog) {
    ((Dog) a).bark();
} else {
    System.out.print("not a dog");
}

What is printed?

  • A

    ClassCastException

  • B

    Compile-time error

  • C

    not a dog

    check_circle
  • D

    Woof

Explanation

The instanceof check prevents the unsafe cast. a is just an Animal, not a Dog.

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

Related questions