ProgrammingHardProduct-company interview pattern

What is printed?

What is printed?
class P {
    static int c = 0;
    P() { c++; }
}
class Q extends P {
    Q() { c += 10; }
}
// in main:
new P(); new Q(); new Q();
System.out.print(P.c);
  1. A. 21
  2. B. 23
  3. C. 3
  4. D. 12

Correct answer: B. 23

c is one shared static field. new P() → 1. Each new Q() first runs P() through the implicit super() (+1) and then its own body (+10): 1 + 11 + 11 = 23. 21 forgets the implicit super() call.

More OOP with C++ and Java questions

Exams that ask this topic