Interview Q&A / Object-Oriented Programming

AdvancedQuick answer1 min readUpdated 3 Oct 2026

Predict the output: a parent reference holds a child object that hides the parent's field. Which value do you get?

SHORT ANSWER

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

java
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: C

Avoid 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.

#polymorphism#java#field-hiding

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.