ProgrammingHardGATE CS · TCS Digital · Advanced

What is printed?

What is printed?
class A {
    A() { init(); }
    void init() { System.out.print("A"); }
}
class B extends A {
    int v = 5;
    B() { super(); System.out.print(v); }
    void init() { System.out.print("B" + v); }
}
// in main:
new B();
  1. A. B55
  2. B. B05
  3. C. A5
  4. D. B00

Correct answer: B. B05

A's constructor calls the overridden init() before B's field initialisers have run, so v is still 0 and 'B0' is printed; afterwards v = 5 and B's constructor body prints 5.

More OOP with C++ and Java questions

Exams that ask this topic