ProgrammingVery hardProduct-company MCQ pattern

What is printed?

What is printed?
class A {
    A() { System.out.print("A "); init(); }
    void init() { System.out.print("A.init "); }
}
class B extends A {
    int x = 10;
    B() { System.out.print("B "); }
    void init() { System.out.print("x=" + x + " "); }
}
// in main:
new B();
  1. A. A x=10 B
  2. B. A x=0 B
  3. C. A x=0 B x=10
  4. D. A B x=10

Correct answer: B. A x=0 B

Java's constructor chaining implicitly calls the superclass constructor first; inside A's constructor, the virtual call init() dispatches to B's override (because the object's actual runtime type is already B), but B's field x has not yet been initialized at this point (field initializers run after the super() call completes, right before B's own constructor body), so x reads as its default value 0.

More OOP with C++ and Java questions

Exams that ask this topic