ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    Base() { System.out.print("Base "); }
    protected Base(int x) { System.out.print("Base(int) "); }
}
class Sub extends Base {
    Sub() { super(5); System.out.print("Sub "); }
}
class Grand extends Sub {
    Grand() { System.out.print("Grand "); }
}
public class Main {
    public static void main(String[] args) { new Grand(); }
}
  1. A. Base Sub Grand
  2. B. Base(int) Sub Grand
  3. C. Grand Sub Base(int)
  4. D. Compile-time error: Grand cannot call a protected constructor of Base indirectly

Correct answer: B. Base(int) Sub Grand

Grand()'s implicit super() call goes to Sub(), which explicitly calls super(5), reaching Base(int) (protected is fine since Sub is a subclass), printing Base(int). Sub()'s own body then prints Sub, and finally Grand()'s body prints Grand. Base's no-arg constructor is never invoked at all.

More OOP with C++ and Java questions

Exams that ask this topic