ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
class P {
    P() { show(); }
    void show() { System.out.print("P"); }
}
class C extends P {
    int v = 7;
    String s = "x";
    C() { show(); }
    void show() { System.out.print(v + s); }
}
// in main:
new C();
  1. A. P7x
  2. B. 7x7x
  3. C. 0null7x
  4. D. Pnull7x

Correct answer: C. 0null7x

P's constructor runs before C's field initialisers, yet show() dispatches to C, which sees the defaults 0 and null. After super() returns, v = 7 and s = "x" are set, and C's constructor prints 7x.

More OOP with C++ and Java questions

Exams that ask this topic