Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 3/5

public class Animal {}
public class Dog extends Animal {}
public class Cat extends Animal {}
Animal a = new Cat();
Dog d = (Dog) a;

What happens?

  • A

    Compile-time error

  • B

    NullPointerException

  • C

    ClassCastException at runtime

    check_circle
  • D

    Runs successfully

Explanation

The cast compiles because Dog is a subclass of Animal, but at runtime the object is actually a Cat, causing ClassCastException.

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

Related questions