Sub topic 10
Why Fields Don't Behave Polymorphically
In earlier chapters you saw that when you call an instance method, Java looks at the real object to decide which version runs. You might expect fields to work the same way. They do not. This chapter shows what happens instead, why it surprises people, and how to write classes that avoid the problem.
A Quick Reminder of the Terms
A field is a variable that belongs to an object, such as String name. The declared type is the type written on the variable, like Parent in Parent p. The runtime type is the class of the object the variable actually points to, like Child in new Child().
For instance methods, Java uses the runtime type. For fields, it uses the declared type, and it makes that choice when the code is compiled, before the program runs.
The Surprise in Code
Here is a parent class and a child class. Both declare a field called name. Both also have a method that returns it.
class Parent {
String name = "Parent";
String getName() {
return name;
}
}
class Child extends Parent {
String name = "Child";
@Override
String getName() {
return name;
}
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name); // Parent
System.out.println(p.getName()); // Child
System.out.println(((Child) p).name); // Child
}
}Save this as Main.java, then run javac Main.java and java Main. The output is:
Parent
Child
ChildThe variable p and the object are the same in all three lines, but the results differ:
p.namereads a field. Java looks at the declared typeParentand readsParent's field.p.getName()calls an instance method. Java looks at the runtime typeChildand runsChild's method, which returnsChild's field.((Child) p).namefirst castsptoChild. A cast tells the compiler to treat a value as another type. Now the declared type isChild, so Java readsChild's field.
One Object, Two Fields
When Child declares its own name, it does not replace the parent's field. It adds a second one. Every Child object holds two separate variables called name, one from Parent and one from Child.
This is called field hiding. A hidden field is a superclass field that a subclass field with the same name makes harder to reach. The parent's field is still there and still has its own value. You just need a different route to reach it.
Inside Child, you can reach both fields. Plain name means the child's field. super.name means the parent's field.
class Parent {
String name = "Parent";
}
class Child extends Parent {
String name = "Child";
void showBoth() {
System.out.println("this.name = " + this.name);
System.out.println("super.name = " + super.name);
}
}
public class Main {
public static void main(String[] args) {
new Child().showBoth();
}
}Output:
this.name = Child
super.name = ParentA Sneakier Version: Parent Methods Read Parent Fields
The confusing case is usually not p.name. It is a method in the parent class that reads the field.
class Parent {
String name = "Parent";
String describe() {
return "I am " + name;
}
}
class Child extends Parent {
String name = "Child";
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
System.out.println(c.name); // Child
System.out.println(c.describe()); // I am Parent
}
}The variable c is declared as Child, yet describe() prints I am Parent. The reason is that describe() lives in Parent. Inside Parent's code, the word name was linked to Parent's field when that code was compiled. The method has no way of knowing that a subclass later added its own name.
This bug is easy to miss. The child "sets" a new name, a method inherited from the parent ignores it, and the compiler gives no error.
Why Java Works This Way
Java treats methods and fields differently on purpose.
- A method is behavior. Polymorphism exists so that different objects can behave differently when asked the same thing, so methods are chosen at runtime.
- A field is storage. It is a slot of memory in the object. The compiler decides which slot an expression refers to, using the declared type, because that is all it can see while compiling.
Because the compiler fixes field access early, reading a field is fast and predictable. The cost is that fields cannot take part in polymorphism.
| Member | How Java chooses | Chosen when |
|---|---|---|
| Instance method | Runtime type of the object | While the program runs |
| Field (instance or static) | Declared type of the variable | At compile time |
| Static method | Declared type of the variable | At compile time |
| Private method | The class that wrote the call | At compile time |
The Fix: Don't Redeclare Fields
The cure is simple: never give a subclass a field with the same name as a superclass field. If the subclass needs a different value, set the parent's single field to that value instead. There are two common ways to do this.
Option 1: Pass the Value to the Parent Constructor
Make the field private and let the subclass supply its value through super(...), a call that runs the parent's constructor.
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
String getName() {
return name;
}
String describe() {
return "I am a " + name;
}
}
class Dog extends Animal {
Dog() {
super("Dog");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.getName()); // Dog
System.out.println(a.describe()); // I am a Dog
}
}There is only one name field now, so every piece of code sees the same value.
Option 2: Override a Method Instead of a Field
If the value is fixed for each class, use a method that each subclass overrides. Methods are polymorphic, so the parent's code picks up the child's answer.
class Animal {
String kind() {
return "Animal";
}
String describe() {
return "I am a " + kind();
}
}
class Cat extends Animal {
@Override
String kind() {
return "Cat";
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat();
System.out.println(a.describe()); // I am a Cat
}
}Summary
- Fields are chosen by the declared type, at compile time.
- Instance methods are chosen by the runtime type, while the program runs.
- A subclass field with the same name hides the parent's field. The object then holds both.
- Code written in the parent class always reads the parent's field.
- To get different values per subclass, pass values to the parent constructor or override a method. Do not redeclare the field.
Exercise
Given class A { int x = 1; int getX() { return x; } } and class B extends A { int x = 2; @Override int getX() { return x; } }, what do these lines print? A obj = new B(); System.out.println(obj.x); System.out.println(obj.getX()); System.out.println(((B) obj).x);
Show answer
They print 1, then 2, then 2. obj.x uses the declared type A, so it reads A's field. obj.getX() runs B's overriding method, which reads B's field. The cast makes the declared type B, so ((B) obj).x reads B's field.
Exercise
A Vehicle class has int wheels = 4; and a method String info() { return wheels + " wheels"; }. A Bike subclass declares int wheels = 2; and nothing else. What does new Bike().info() return, and how would you fix it?
Show answer
It returns "4 wheels". The info() method is written in Vehicle, so it reads Vehicle's wheels field. To fix it, remove the field from Bike, make Vehicle's field private, give Vehicle a constructor that takes the wheel count, and have Bike call super(2). Another fix is to replace the field with a wheels() method that Bike overrides to return 2.
Exercise
Inside a subclass that hides a parent field called count, how do you read the parent's value?
Show answer
Use super.count. Plain count or this.count reads the subclass's own field.