Polymorphism

AP Computer Science A· difficulty 2/5

public class Animal {
    public String sound() { return "generic"; }
}
public class Dog extends Animal {
    public String sound() { return "Woof"; }
}
Animal a = new Dog();
System.out.println(a.sound());

What is printed?

  • A

    Woof

    check_circle
  • B

    generic

  • C

    Compile-time error

  • D

    Runtime error

Explanation

Java uses dynamic dispatch: even though <code>a</code> is declared as <code>Animal</code>, the actual object is a <code>Dog</code>, so <code>Dog.sound()</code> is invoked at runtime.

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

Related questions