Vivyen Andzuana Vivyen Andzuana - 1 year ago 62
Java Question

Non overridden method doesn't show subclass field

Please help me on this topic:

class Parent{
String st = "external";

void print() {
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 Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download