简体   繁体   中英

Why baseclass calls method of subclass?

I encounter some code like the following:
BaseClass:

public class BaseClass {
    String name = "Base";

    public BaseClass() {
        printName();
    }

    public void printName() {
        System.out.println(name + "——Base");
    }
}

DrivedClass:

public class SubClass extends BaseClass {
    String name = "Sub";

    public SubClass() {
        printName();
    }

    public void printName() {
        System.out.println(name + "——Sub");
    }

    public static void main(String[] args) {
        new SubClass();
    }
}

When run the code, the output is:

null——Sub
Sub——Sub

while it should be:

Base——Base
Sub——Sub

I wonder why the BaseClass constructor calls the SubClass method, can anybody explain this? Thanks in advance.

The first line( "null——Sub" ) is printed as a result of printName() of SubClass being called from the BaseClass constructor. When printName() is called from BaseClass constructor, since there is an overridden method available in the SubClass , that printName() is called.

At this point of time, since the SubClass constructor is not yet called, the name field of SubClass is undefined and thus prints null .

The second line( "Sub——Sub" ) is printed as a result of printName() of SubClass being called from the SubClass constructor. This time around, the instance fields are loaded and thus, the name prints the proper value (ie) "Sub".

The thing to note here is that, both the times, the printName() method of SubClass is only called. Just that the first time around(because it's called from the super class constructor), its instance fields are not defined and the second time around, they are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM