我編寫了一個帶有超類和兩個子類的簡單代碼,以跟踪順序或初始化。我的靜態初始值設定項的行為符合預期並按正確順序進行初始化。但是我的實例初始化程序似乎在我的構造函數之前運行了兩次。我知道這是初始化的順序,但我試圖獲得一些洞察力並遵循流程並且不知道為什麼實例初始化程序打印兩次。這是我的代碼和我收到的輸出。(見下文)
class Bird{
static {System.out.println("Static Initializer 1");}
{System.out.println("Instance Initializer 1");}
int feathers = 0;
Bird(int x){ this.feathers = x; }
Bird fly() { return new Bird(1); }
}
class Parrot extends Bird {
static {System.out.println("Static Initializer 2");}
{System.out.println("Instance Initializer 2");}
protected Parrot(int y){ super(y); }
protected Parrot fly(){ return new Parrot(2); }
}
public class Macaw extends Parrot {
static {System.out.println("Static Initializer 3");}
{System.out.println("Instance Initializer 3");}
public Macaw(int z){ super(z); }
public Macaw fly(){ return new Macaw(3); }
public static void main(String... args){
Bird p = new Macaw(4);
System.out.println(((Parrot)p.fly()).feathers);
}
}
結果:
可能是因為您的fly()
方法實際上創建了一個新實例:
public Macaw(int z){ super(z); }
public Macaw fly(){ return new Macaw(3); } <---- NEW
public static void main(String... args){
Bird p = new Macaw(4); // Instance 1
System.out.println(((Parrot)p.fly()).feathers); // Calling fly() creates instance 2
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句