ProgrammingHardProduct-company MCQ pattern

What is printed?

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

Correct answer: B. C0 C10

P's constructor runs before C's field initialisers, but the call show() is still dispatched to C.show, which sees x at its default value 0. After construction x is 10. Calling overridable methods from a constructor is a known trap.

More OOP with C++ and Java questions

Exams that ask this topic