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 {}
// Usage:
Animal a = new Cat();
Dog d = (Dog) a;

What occurs?

  • A

    ClassCastException at runtime

    check_circle
  • B

    Compiles and runs successfully

  • C

    Compile error

  • D

    Casts but d is null

Explanation

The cast compiles since Cat and Dog both extend Animal, but at runtime the actual object is a Cat, which is not a Dog, so a ClassCastException is thrown.

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

Related questions