我遇到了问题。在继承时,基构造函数调用虚方法,为什么类是Dervied并调用Dervied方法?
public class Dervied extends Base {
private String name = "dervied";
public Dervied() {
System.out.println(this.getClass().toString());
this.tellName();
}
public void tellName() {
System.out.println("Dervied tell name: " + name);
}
public static void main(String[] args) {
Base base = new Dervied();
}
}
class Base {
private String name = "base";
public Base() {
System.out.println(this.getClass().toString());
this.tellName();
}
public void tellName() {
System.out.println("Base tell name: " + name);
}
}
结果是:
class Dervied
Dervied tell name: null
class Dervied
Dervied tell name: dervied
但是,为什么下面的代码不会按预期运行?环境是jdk1.8.0_60和Windows 10.当new Dervied()
遇到Dervied()
方法,并调用基础构造函数Base()
。但是为什么Base()
的印刷类是Dervied
?而this.tellName()
将Dervied
类中的方法称为多态?
字段不是多态的。 – Savior