Polymorphism

AP Computer Science A· difficulty 4/5

Animal +sound():String Dog +sound():String Cat +sound():String

Given the UML hierarchy shown and:

<code class="language-java">class Animal { public String sound() { return "..."; } } class Dog extends Animal { public String sound() { return "Woof"; } } class Cat extends Animal { public String sound() { return "Meow"; } } Animal[] arr = {new Dog(), new Cat(), new Animal()}; for (Animal a : arr) System.out.print(a.sound() + " "); </code></pre> What is printed?

  • A

    Compile error: cannot store Dog in Animal[]

  • B

    Woof Meow ...

    check_circle
  • C

    ... ... ...

  • D

    Dog Cat Animal

Explanation

Java uses the runtime (dynamic) type for instance-method dispatch. Each element calls its own overridden <code>sound()</code>. The Dog returns "Woof", the Cat returns "Meow", and the plain Animal returns "...".

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

Related questions