Polymorphism

AP Computer Science A· difficulty 4/5

Given:

<code>class Animal { public String sound() { return "..."; } } class Dog extends Animal { public String sound() { return "Woof"; } } Animal a = new Dog(); System.out.println(a.sound()); </code></pre> The output is

  • A

    compile error

  • B

    runtime error

  • C

    ...

  • D

    Woof

    check_circle

Explanation

Java uses dynamic (runtime) method dispatch for instance methods. The compile-time type is Animal, but the runtime object is Dog, so Dog.sound() executes.

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

Related questions