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();- A. P C10
- B. C0 C10
- C. C10 C10
- 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
- What is printed? java class T { static { System.out.print("S"); } { System.out.print("I"); } T() { System.out.print("C"); } } // in main…
- What is printed? java // static methods of the main class: static int f() { int x = 1; try { return x; } finally { x = 5; } } static int…
- What is printed? java System.out.print(1 + 2 + "3" + 4 + 5);
- What is printed? java // static methods of the main class: static void change(StringBuilder sb) { sb.append("X"); sb = new…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); l.remove(1); System.out.print(l + " ")…
- What is printed? java List<Integer> list = new ArrayList<>(List.of(1, 2, 3)); for (Integer i : list) if (i == 2) list.remove(i)…