Given the following code: class Base { int x = 10; } class Derived extends Base { int x = 20; } Base b = new Base(); Derived d = new Derived ( ); Base bd = new Derived(); The statement System.out.println(b.x + " " + d.x + " " + bd.x); will produce the output
-
10 20 20
-
20 10 20
-
10 20 10
-
20 20 10
To solve this question, the user needs to understand the concept of inheritance in Java, as well as the difference between instance variables and class variables.
The Base class has an instance variable x with a value of 10, and the Derived class has an instance variable x with a value of 20. When a Derived object is created, it will have both the x variables, but when a Base object is created, it will only have the x variable from the Base class. When a Derived object is assigned to a Base reference, the Base reference can only access the x variable of the Base class.
Now, let's go through each option and explain why it is right or wrong:
A. 10 20 10: This option is correct. When b.x is evaluated, it refers to the x variable of the Base class, which has a value of 10. When d.x is evaluated, it refers to the x variable of the Derived class, which has a value of 20. When bd.x is evaluated, it refers to the x variable of the Base class (since bd is a Base reference), which has a value of 10.
B. 20 20 10: This option is incorrect. b.x is 10 (the x variable of the Base class), d.x is 20 (the x variable of the Derived class), and bd.x is 10 (the x variable of the Base class).
C. 10 20 20: This option is incorrect. b.x is 10 (the x variable of the Base class), d.x is 20 (the x variable of the Derived class), and bd.x is 20 (the x variable of the Derived class`).
D. 20 10 20: This option is incorrect. b.x is 10 (the x variable of the Base class), d.x is 20 (the x variable of the Derived class), and bd.x is 20 (the x variable of the Derived class`).
Therefore, the answer is: A. 10 20 10
Java field access is NOT polymorphic — it's resolved at compile time based on the reference (declared) type, not the runtime object type (unlike method overriding, which IS dynamically dispatched). b.x uses Base's field: 10. d.x is accessed through a Derived-typed reference, so it uses Derived's field: 20. bd.x is declared as type Base (even though it points to a Derived object at runtime), so field access resolves against Base's x, giving 10 — this is called 'field hiding' or 'field shadowing', distinct from method overriding. So the output is '10 20 10'. The wrong options assume field access behaves polymorphically like method calls (e.g., bd.x resolving to 20), which is a very common Java misconception this question is specifically testing.