Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What does this Java code print when a parent reference holds a child object?

SHORT ANSWER

Methods are looked up on the real object at runtime, so the child version runs. Fields are looked up on the reference type at compile time, so the parent field is read. Fields are never polymorphic.

Explain it simply

Imagine a student wearing a school-uniform badge that says "Vehicle", while the person inside is really a "Car". If you ask the badge what is written on it, you get "Vehicle". If you ask the person to make a sound, the Car answers. Fields follow the badge (reference type). Methods follow the person (actual object).

Example

java
class Vehicle {
    String type = "Vehicle";
    String sound() { return "generic"; }
}
class Car extends Vehicle {
    String type = "Car";
    @Override String sound() { return "vroom"; }
}

Vehicle v = new Car();
System.out.println(v.type);          // prints: Vehicle
System.out.println(v.sound());       // prints: vroom
System.out.println(((Car) v).type);  // prints: Car

What to say in the interview

"Instance method calls use dynamic dispatch, so the overridden method in Car runs. Field access is resolved at compile time using the declared type, so v.type reads Vehicle's field. The Car class has its own separate field that merely hides the parent's. Because of this, exposing fields and relying on hiding is bad design; use getters, which are polymorphic."

Common mistakes

  • Expecting v.type to print Car.
  • Treating field hiding as if it were overriding.

#java#oop#polymorphism

Related questions

Practise more Java questions

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

Open Java 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.