Object-Oriented Programming · Question 14 · Hard

What is the output of the following Java code?

class A {
    int x = 10;
    int getX() { return x; }
}
class B extends A {
    int x = 20;
    int getX() { return x; }
}
// in main:
A o = new B();
System.out.println(o.x + " " + o.getX());
  1. 10 10
  2. 10 20
  3. 20 20
  4. 20 10
Answer and explanation

Answer: B. 10 20

Explanation: Fields are not polymorphic: o.x is resolved from the reference type A and gives 10. getX() is overridden, so the call runs B's version and returns B's x, which is 20.

Previous: What is the output of the following Java code? · Next: Which SOLID principle states that objects of a subclass should be usable…

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