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[]
- Bcheck_circle
Woof Meow ...
- 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 "...".