Object-Oriented Programming · Question 30 · Hard

What is the output of the following Java code?

class P {
    P() { show(); }
    void show() { System.out.println("P"); }
}
class C extends P {
    int x = 5;
    void show() { System.out.println("C " + x); }
}

// in main:
new C();
  1. C 0
  2. P
  3. C 5
  4. Compilation error
Answer and explanation

Answer: A. C 0

Explanation: P's constructor runs first and calls show(), which is dynamically dispatched to C.show(). C's field initializer x = 5 has not run yet at that point, so x still holds its default value 0.

Previous: What is the output of the following Python code?

Practise object-oriented programming

Try a fresh set of object-oriented programming questions with an explanation after every answer, free and without signing up: Object-Oriented Programming practice. Or sit a full placement mock test.

More object-oriented programming questions

More technical & programming practice

DBMS · SQL · Operating Systems · Computer Networks · Software Engineering · Cloud & DevOps · GenAI Basics · Pseudo-code

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge