ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    Base() { System.out.print("Base "); }
}
class Mid extends Base {
    Mid() { System.out.print("Mid "); }
}
class Leaf extends Mid {
    Leaf() { super(); System.out.print("Leaf "); }
}
public class Main {
    public static void main(String[] args) { new Leaf(); }
}
  1. A. Leaf Mid Base
  2. B. Base Mid Leaf
  3. C. Base Leaf Mid
  4. D. Compile-time error: super() in Leaf must call Base(), not Mid()

Correct answer: B. Base Mid Leaf

super() in Leaf() calls its immediate superclass's constructor, Mid(), not Base() directly. Mid()'s own implicit super() call reaches Base() first, printing Base, then Mid's body prints Mid, then control returns to Leaf's body, printing Leaf. Result: Base Mid Leaf.

More OOP with C++ and Java questions

Exams that ask this topic