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);- A. 21
- B. 23
- C. 3
- 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
- What is printed? java class A { int x = 10; A() { x = 20; } { x = 30; } } // in main: System.out.print(new A().x);
- What is printed? java interface I { default String who() { return "I"; } } class P { public String who() { return "P"; } } class C extends…
- What is printed? java StringBuilder a = new StringBuilder("hi"); StringBuilder b = new StringBuilder("hi"); System.out.print(a.equals(b) +…
- What happens when this Java code is compiled and run? java Object o = new ArrayList<String>(); List<String> l = (List<String>) o; String s…
- What is printed? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } A& operator=(const A&) { cout << "="; return this; } }…
- What is printed? java String s = "b"; switch (s) { case "a": System.out.print("A"); case "b": System.out.print("B"); case "c"…