Vivyen Andzuana Vivyen Andzuana - 3 days ago 5
Java Question

Non overridden method doesn't show subclass field

Please help me on this topic:

class Parent{
String st = "external";

void print() {
System.out.println(st);
System.out.println(this.st);
}
}
class Child extends Parent{
String st = "inner";
}
public static void main(String[] args) {
new Child().print(); // shows "external"
}


why print() called on subclass doesn't show string - "inner" ?

Answer

why print() called on subclass doesn't show string - "inner" ?

Because member variables cannot be overridden. The member variable st in class Child does not override the member variable st in class Parent. The two member variables are two separate variables, which happen to have the same name.

The methods in class Parent see the member variable st that is defined in class Parent, and not the one in class Child, even if the object is really an instance of class Child.

Only methods can be overridden.

More information in Oracle's Java Tutorials: Hiding Fields (thanks @JonK).

Comments