ProgrammingHardAccenture · Infosys

What is printed?

What is printed?
class P { P() { init(); } void init() { } }
class C extends P {
    int v = 5;
    void init() { System.out.print(v); }
}
// in main:
new C();
  1. A. 5
  2. B. 0
  3. C. null
  4. D. Compile error

Correct answer: B. 0

The superclass constructor runs before C's field initialisers, and the overridden init is called while v still holds its default 0.

More OOP with C++ and Java questions

Exams that ask this topic