Fields are not overrideable. If a class declares a field named string
, and a subclass also declares a field named string
, then there are two separate fields named string
. For example, this program:
class Parent {
public String string = "parent";
public int getInt() {
return 1;
}
}
class Child extends Parent {
public String string = "child"; // does not override Parent.string
// overrides Parent.getInt():
public int getInt() {
return 2;
}
}
public class Main {
public static void main(final String... args) {
Child child = new Child();
System.out.println(child.string); // prints "child"
System.out.println(child.getInt()); // prints "2"
Parent childAsParent = child;
System.out.println(childAsParent.string); // prints "parent" (no override)
System.out.println(childAsParent.getInt()); // prints "2" (yes override)
}
}
prints
child
2
parent
2
because childAsParent
has type Parent
, so refers to the field declared in Parent
, even though the actual instance has runtime-type Child
.
So if you modify your demonstration to use a method rather than a field, you will see the results you were expecting.