What does this Java code print when a parent reference holds a child object?
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
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: CarWhat 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.typeto print Car. - Treating field hiding as if it were overriding.