Field hiding vs method overriding
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fields and methods follow different rules. A field is picked by the reference type at compile time; an overridden instance method is picked by the object at run time. Reuse a parent's field name in a child, and the two can disagree.
A same-named field is a second field
Field hiding happens when a child class declares a field with the same name as a field in its parent. The child object then holds both fields, and the compiler picks which one you read from the reference type, not from the object.
Parent has String name = "parent", and Child extends Parent declares its own String name = "child". Nothing is replaced: a Child object now holds two name fields.
Example 1 · One object, two name fields
class Parent { String name = "parent";}
class Child extends Parent { String name = "child";}
public class HidingDemo { public static void main(String[] args) { Parent p = new Child(); Child c = (Child) p; System.out.println(p.name); System.out.println(c.name); System.out.println(((Child) p).name); }}parent child child
What this code does
pandcpoint to the same object, butp.namereads theParentfield andc.namereads theChildfield.- The cast changes the reference type, so
((Child) p).namereads the child's field.
So a cast can change which field you read: ((Child) p).name gives "child". Fields are never dispatched at run time; Dynamic method dispatch (opens in a new tab) applies only to overridden instance methods.
Fields follow the variable, methods follow the object
If Car overrides getSpeed(), then v.getSpeed() runs the car's version, even through a Vehicle v. But v.speed still reads Vehicle's field. Same object, two answers.
Example 2 · Field vs method on the same object
class Vehicle { int speed = 60;
int getSpeed() { return speed; }}
class Car extends Vehicle { int speed = 120;
@Override int getSpeed() { return speed; }}
public class SpeedDemo { public static void main(String[] args) { Vehicle v = new Car(); System.out.println("Field: " + v.speed); System.out.println("Method: " + v.getSpeed()); }}Field: 60 Method: 120
What this code does
v.speedis a field, picked from the reference typeVehicle: 60.v.getSpeed()is overridden, soCar's version runs, and insideCarplainspeedmeansCar's field: 120.
A short rule helps: fields and static methods look at the variable; overridden instance methods look at the object. Try it on the rounds below before reading on.
Predict the output
Field or method?
Read the code and pick what it prints.
Round 1 of 2
Both classes declare ink, and GelPen overrides ink().
Inside the classes: this, super and the parent's methods
Inside Child, plain name (or this.name) means the child's field, and super.name reaches the hidden one. Inside Parent, plain name always means the parent's field, even when the object is a Child.
Example 3 · Inherited code reads the parent's field
class Account { String type = "Account";
String label() { return "Account"; }
void show() { System.out.println("field: " + type + ", method: " + label()); }}
class SavingsAccount extends Account { String type = "Savings";
@Override String label() { return "Savings"; }
void showBoth() { System.out.println("this.type = " + this.type + ", super.type = " + super.type); }}
public class InheritedDemo { public static void main(String[] args) { SavingsAccount s = new SavingsAccount(); s.show(); s.showBoth(); }}field: Account, method: Savings this.type = Savings, super.type = Account
What this code does
show()is written inAccount, so itstypemeansAccount's field; its call tolabel()is dispatched toSavingsAccount.- Inside the child,
this.typeis the child's field andsuper.typereaches the hidden parent field.
But if that parent method calls an overridden method, the child's version runs. When tracing, ask for every name: is it a field (look at the declared type, or the class where the code is written) or an overridden method (look at the object)?
Static methods are hidden, not overridden
Method hiding happens when a child class declares a static method with the same signature as a static method in its parent. The call is chosen by the compiler from the reference type or class name, so the object never decides.
A static method belongs to the class, not to an object, and overriding needs an object. So with Parent p = new Child();, p.info() runs Parent.info().
Example 4 · Static methods are picked by the reference type
class Parent { static void info() { System.out.println("Parent.info (static)"); }
void show() { System.out.println("Parent.show"); }}
class Child extends Parent { static void info() { System.out.println("Child.info (static)"); }
@Override void show() { System.out.println("Child.show"); }}
public class StaticHidingDemo { public static void main(String[] args) { Parent p = new Child(); p.info(); p.show(); Child.info(); }}Parent.info (static) Child.show Child.info (static)
What this code does
p.info()is static, so the compiler picksParent.info()from the reference type; the object is ignored.p.show()is an instance method and is overridden, soChild.showruns. WritingChild.info()makes the choice clear.
Example 5 · Mistake: @Override on a static method
class Parent { static void info() { System.out.println("Parent.info"); }}
class Child extends Parent { @Override static void info() { System.out.println("Child.info"); }}
public class StaticOverrideDemo { public static void main(String[] args) { Child.info(); }}StaticOverrideDemo.java:8: error: static methods cannot be annotated with @Override
@Override
^
1 errorWhat this code does
@Overrideasks the compiler to confirm that a method overrides another. A static method never overrides, so javac refuses.- Remove
@Override: the child's staticinfo()then simply hides the parent's.
Call static methods through the class name, like Child.info(), and there is nothing to confuse. Calling them through a variable only looks like a polymorphic call.
How to avoid the surprises
Field hiding is legal Java, but it almost always causes bugs. Keep fields private, never repeat a parent's field name, and pass a child's value up with super(...).
Example 6 · The clean design: private field, value through super()
class Ticket { private final int fare;
Ticket(int fare) { this.fare = fare; }
int getFare() { return fare; }
String kind() { return "General"; }}
class AcTicket extends Ticket { AcTicket() { super(1700); }
@Override String kind() { return "AC"; }}
public class CleanDemo { public static void main(String[] args) { Ticket[] list = { new Ticket(300), new AcTicket() }; for (Ticket t : list) { System.out.println(t.kind() + ": Rs. " + t.getFare()); } }}General: Rs. 300 AC: Rs. 1700
What this code does
AcTicketdoes not declare its ownfarefield; it passes its value to the parent withsuper(1700). There is one field, so nothing is hidden.- What differs by type, the kind, comes from an overridden method, which always follows the object.
If a value really differs per child class, read it through an overridden method, which always follows the object. Then p.name-style surprises cannot happen.
Next step
Check your understanding
12 quick questions