ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Animal {
    void speak() { System.out.print(".."); }
}
class Dog extends Animal {
    void speak() { System.out.print("Woof"); }
}
class Puppy extends Dog {
    void speak() { System.out.print("Yip"); }
}
// in main:
Animal a = new Puppy();
a.speak();
  1. A. ..
  2. B. Woof
  3. C. Yip
  4. D. Compile-time error: Animal has no speak() that matches Puppy

Correct answer: C. Yip

Method calls in Java are dispatched using the object's actual runtime class, regardless of the reference's declared type. a holds a Puppy, and Puppy overrides speak() again (overriding Dog's override), so the most-derived version, Yip, runs.

More OOP with C++ and Java questions

Exams that ask this topic