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(); }
}- A. Animal
- B. Bird
- C. Penguin
- 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
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(const Base&) { cout << "BaseCopy "; } }; struct Derived : Base {…
- What is printed? cpp int f() { std::cout << "f "; return 1; } int g() { std::cout << "g "; return 2; } int a = f(); int b = g(); int…
- What is printed? cpp struct X { int id; X(int i) : id(i) { std::cout << "X" << id << " "; } ~X() { std::cout << "~X" << id << " "; } }…
- What is printed? cpp struct Animal { void speak() { std::cout << "Animal"; } }; struct Dog : Animal { void speak() { std::cout << "Dog"; }…
- What is wrong with this generic class? java class Factory<T> { T create() { return new T(); } }
- What is printed? java class A { static int x = init("x", 1); static { System.out.print("sA "); } static int y = init("y", 2); static int…