ProgrammingHardIBM · Deloitte pattern

What is printed?

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

Correct answer: B. A(int)=10 A()

this(10) redirects construction to A(int), which runs to completion first (its own implicit super() to Object runs silently, then it prints A(int)=10). Control then returns to A()'s remaining body, which prints A(). Result: A(int)=10 A().

More OOP with C++ and Java questions

Exams that ask this topic