为什么我的 Java 实例初始化程序初始化两次?
Why are my Java Instance Initializers initializing twice?
我编写了一个简单的代码,其中包含一个超级 class 和两个子 class 以跟踪顺序或初始化。我的静态初始化程序表现得像预期的那样,并以正确的顺序进行初始化。但是我的实例初始化程序似乎在我的构造函数之前 运行 两次。我知道这是初始化的顺序,但我试图获得一些洞察力并遵循流程并且不知道为什么实例初始化程序打印两次。这是我的代码和我收到的输出。 (见下文)
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
}
我编写了一个简单的代码,其中包含一个超级 class 和两个子 class 以跟踪顺序或初始化。我的静态初始化程序表现得像预期的那样,并以正确的顺序进行初始化。但是我的实例初始化程序似乎在我的构造函数之前 运行 两次。我知道这是初始化的顺序,但我试图获得一些洞察力并遵循流程并且不知道为什么实例初始化程序打印两次。这是我的代码和我收到的输出。 (见下文)
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
}