ProgrammingHardTCS NQT · Infosys pattern

What is printed?

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

Correct answer: A. Base() Sub() Sub(int)

Sub(int) calls this(), redirecting entirely to Sub(). Sub() in turn explicitly calls super() first (running Base(), printing Base()) and then its own body (printing Sub()). Control then returns to Sub(int)'s remaining body, printing Sub(int). Only one of this()/super() is allowed per constructor, and each constructor here only uses one, so there's no conflict.

More OOP with C++ and Java questions

Exams that ask this topic