Predict the output: a parent reference holds a child object that hides the parent's field. Which value do you get?
Methods are chosen by the object's real type, but fields are chosen by the reference type. So p.name gives the parent's value while p.get() runs the child's method.
Explain it simply
Overriding applies to methods only. A field with the same name in a child does not replace the parent's field; it sits beside it as a second, separate field. Java picks fields at compile time from the variable's declared type.
Example
class P {
String name = "P";
String get() { return "P"; }
}
class C extends P {
String name = "C";
@Override String get() { return "C"; }
}
P p = new C();
System.out.println(p.name); // prints: P
System.out.println(p.get()); // prints: C
System.out.println(((C) p).name); // prints: CAvoid giving a child field the same name as a parent field. Expose the value through a method if different classes need to vary it.
What to say in the interview
"Only instance methods are dispatched dynamically. Fields and static methods are resolved by the declared type of the reference. So p.name reads the parent's field, while p.get() runs the child's override."
Common mistakes
- Expecting field access to behave like method overriding.