Why baseclass calls method of subclass?
- by twlkyao
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.