1Z0-819 · Question #171
Given: ``java package test.t1; public class A { public int x = 42; protected A() { } } package test.t2; import test.t1.; public class B extends A { int x = 17; public B() { super(); } } package…
The correct answer is A. 42. Option A (42) is correct because in Java, field access is statically bound - the compiler resolves obj.x based on the declared type of the reference (A), not the runtime type (B). Even though the object at runtime is a B instance (with x = 17), obj is declared as A, so obj.x…
Question
package test.t1;
public class A {
public int x = 42;
protected A() { }
}
package test.t2;
import test.t1.*;
public class B extends A {
int x = 17;
public B() { super(); }
}
package test;
import test.t1.*;
public class Tester {
public static void main(String[] args) {
A obj = new B(); // line 4
System.out.println(obj.x); // line 5
}
}
What is the result?Options
- A42
- BThe compilation fails due to an error in line 4.
- C17
- DThe compilation fails due to an error in line 3.
How the community answered
(54 responses)- A72% (39)
- B4% (2)
- C7% (4)
- D17% (9)
Explanation
Option A (42) is correct because in Java, field access is statically bound - the compiler resolves obj.x based on the declared type of the reference (A), not the runtime type (B). Even though the object at runtime is a B instance (with x = 17), obj is declared as A, so obj.x reads A's field, which is 42. Option C (17) is the classic trap: unlike method calls, fields are not polymorphically dispatched - B.x simply hides A.x rather than overriding it, so the hidden field is only accessible through a reference typed as B. Options B and D are wrong because the code compiles cleanly - A obj = new B() is a valid upcast (B extends A), and B's constructor can legally call super() to invoke A's protected constructor since B is a subclass.
Memory tip: "Methods override, fields hide." Override = runtime type wins (dynamic dispatch). Hide = declared type wins (static resolution). Whenever you see a field accessed through an upcast reference on an exam, always use the declared type to find the value.
Topics
Community Discussion
No community discussion yet for this question.