ProgrammingVery hardTCS Digital · Infosys SP

What does this Java program print? class P { P() { init(); } void init() { System.out.print("P "); } } class C extends P { int x = 5; C() { super(); System.out.print(x + " "); } void init() { System.out.print(x + " "); } } public class T { public static void main(String[] a) { new C(); } }

  1. A. 5 5
  2. B. P 5
  3. C. 0 5
  4. D. P 0

Correct answer: C. 0 5

The superclass constructor runs first and calls the overridden init() of C before C's field initialisers execute, so x still has its default 0. After super() returns x is set to 5 and the constructor prints it.

More OOP with C++ and Java questions

Exams that ask this topic