[英]Java - Why is overriden method being called twice (or at least that's what it seems)?
下面有這個輸出。
Hello World!
main.ConstructedDerivedClass:6.0
main.ConstructedDerivedClass:6.0
public class ConstructedDerivedClass extends ConstructedBase {
private static final double version = 6.0;
public static void main(String[] args) {
System.out.println("Hello World!");
ConstructedDerivedClass derivedClass = new ConstructedDerivedClass();
}
public ConstructedDerivedClass() {
showMyAttributes();
}
@Override
protected void showMyAttributes() {
System.out.println(this.getClass().getName() + ":" + version);
}
}
public class ConstructedBase {
private static final double version = 15.0;
public ConstructedBase() {
showMyAttributes();
}
protected void showMyAttributes() {
System.out.println(this.getClass().getName() + ":" + version);
}
}
我希望它只顯示一行,即子類的類(ConstructedDerivedClass)。 但它反而打印兩次。我知道一般你應該避免從構造函數中調用overriden方法,但我想親眼看看它是如何工作的。
實際上,我知道為什么版本在兩行上都是'6.0' - 因為字段被聲明為靜態,當然靜態字段首先被初始化。 但仍然不明白為什么兩行。
任何指導將不勝感激。
這是因為你寫的時候
public ConstructedDerivedClass() {
showMyAttributes();
}
編譯器實際上在字節代碼中調用超級默認構造函數,因此它等效於
public ConstructedDerivedClass() {
super();
showMyAttributes();
}
當一個對象被實例化時,它會在運行自己的構造函數之前對其父類進行implicit, no-args
超構造函數調用。
你可以想象在你的構造函數中總是存在這一行:
public MyClass() {
super(); //If this line is not here, it is implicit.
//rest of the code
}
您可以通過提供自己的explicit, any-args
超構造函數調用來覆蓋它,但它必須是方法的第一行。
public MyClass() {
super(1, "Hello Word", null); //written explicitly, no other super-constructor code will run
//rest of the code
}
當超類沒有定義no-args構造函數時,這可能很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.