ProgrammingHardTCS NQT · Infosys pattern

What is printed?

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

Correct answer: B. A B B(int)

this() in B(int) redirects to B's no-arg constructor instead of letting the compiler insert an implicit super() call directly. B() in turn has its own implicit super() call to A() first (printing A), then its own body (printing B); control then returns to B(int), which prints B(int). Result: A B B(int).

More OOP with C++ and Java questions

Exams that ask this topic