ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Animal {
    Animal() { System.out.print(category() + " "); }
    String category() { return "Animal"; }
}
class Bird extends Animal {
    String category() { return "Bird"; }
}
class Penguin extends Bird {
    String category() { return "Penguin"; }
}
public class Main {
    public static void main(String[] args) { new Penguin(); }
}
  1. A. Animal
  2. B. Bird
  3. C. Penguin
  4. D. Compile-time error: category() is overridden multiple times before Animal's constructor runs

Correct answer: C. Penguin

Animal's constructor calls category() polymorphically; since the object being constructed is already fully typed as a Penguin at the object-identity level (only field initialization is staged, not the vtable/dynamic type in Java), the call dispatches to the most-derived override available, Penguin's, printing Penguin.

More OOP with C++ and Java questions

Exams that ask this topic