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.println("Woof"); }
}
Animal a = new Dog();
((Dog) a).bark();

What is printed?

  • A

    Woof

    check_circle
  • B

    Compile-time error

  • C

    ClassCastException

  • D

    nothing

Explanation

The object is actually a Dog, so the downcast succeeds and bark() runs.

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

Related questions