Creating References Using Inheritance Hierarchies

AP Computer Science A· difficulty 2/5

public class Animal {}
public class Dog extends Animal {
    public void bark() { System.out.println("Woof"); }
}
Animal a = new Dog();
a.bark();

What happens?

  • A

    Compile-time error: bark not in Animal

    check_circle
  • B

    Prints Woof

  • C

    Runtime error

  • D

    Prints nothing

Explanation

Method calls are checked against the declared (compile-time) type. Animal has no <code>bark</code>, so this fails to compile even though the object is a Dog.

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

Related questions