Why baseclass calls method of subclass?

Posted by twlkyao on Stack Overflow See other posts from Stack Overflow or by twlkyao
Published on 2014-05-28T09:07:17Z Indexed on 2014/05/28 9:26 UTC
Read the original article Hit count: 193

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about subclass