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());
- 10 10
- 10 20
- 20 20
- 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
- What is printed when new C() is executed?
- What is the output of the following Java code?
- What is the output of the following Java code?
- Which SOLID principle states that objects of a subclass should be usable…
- A Logger class keeps a list of log entries in a private field and offers only…
- Inside an instance method or constructor in Java, which keyword refers to the…
- Inheritance, as in 'SavingsAccount extends Account', models which kind of…
- Creating an object of a class, for example with new Student() in Java, is…
- Which OOP concept means exposing only the essential features of an object…
- What is the output of the following C++ program?
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