ProgrammingVery hardTCS NQT Prime · Infosys SP

What is printed?

What is printed?
class A {
    A() { init(); }
    void init() { System.out.print("A"); }
}
class B extends A {
    int v = 5;
    B() { System.out.print(v); }
    void init() { System.out.print(v); }
}
// main: new B();
  1. A. 05
  2. B. 55
  3. C. A5
  4. D. 00

Correct answer: A. 05

A's constructor calls the overridden init() before B's field initializers run, so v is still 0; then v = 5 is set and B's constructor prints 5.

More OOP with C++ and Java questions

Exams that ask this topic