問題が発生しました。継承時に、ベースコンストラクタが仮想メソッドを呼び出すと、そのクラスが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