Java构造函数 - 继承层次结构中的执行顺序 [英] Java Constructors - Order of execution in an inheritance hierarchy
问题描述
考虑以下代码
class Meal {
Meal() { System.out.println("Meal()"); }
}
class Bread {
Bread() { System.out.println("Bread()"); }
}
class Cheese {
Cheese() { System.out.println("Cheese()"); }
}
class Lettuce {
Lettuce() { System.out.println("Lettuce()"); }
}
class Lunch extends Meal {
Lunch() { System.out.println("Lunch()"); }
}
class PortableLunch extends Lunch {
PortableLunch() { System.out.println("PortableLunch()");}
}
class Sandwich extends PortableLunch {
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce l = new Lettuce();
public Sandwich() {
System.out.println("Sandwich()");
}
public static void main(String[] args) {
new Sandwich();
}
}
根据我对类成员初始化和顺序的理解构造函数执行。我预计输出为
Based on my understanding of class member initialization and order of constructor execution. I expected the output to be
Bread()
Cheese()
Lettuce()
Meal()
Lunch()
PortableLunch()
Sandwich()
因为我相信甚至在调用main方法之前就已经初始化了类成员。但是当我运行程序时,我有以下输出
as i believe the class members were initialized even before the main method was called. However I had the below output when i ran the program
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()
我的困惑是,Meal()Lunch()和PortableLunch()在Bread()Cheese()和Lettuce()之前运行,即使它们的构造函数在之后调用。
my confusion is whey the Meal() Lunch() and PortableLunch() run before Bread() Cheese() and Lettuce() even though their constructors where called after.
推荐答案
这些是实例字段
private Bread b = new Bread();
private Cheese c = new Cheese();
private Lettuce l = new Lettuce();
如果创建了实例,它们只存在(执行)。
They only exist (execute) if an instance is created.
在您的程序中运行的第一件事是
The first thing that runs in your program is
public static void main(String[] args) {
new Sandwich();
}
超级构造函数被隐式调用为每个构造函数中的第一个东西,即。之前 System.out.println
Super constructors are called implicitly as the first thing in each constructor, ie. before System.out.println
class Meal {
Meal() { System.out.println("Meal()"); }
}
class Lunch extends Meal {
Lunch() { System.out.println("Lunch()"); }
}
class PortableLunch extends Lunch {
PortableLunch() { System.out.println("PortableLunch()");}
}
在 super()
调用之后,实例字段再次被实例化在构造函数代码之前。
After the super()
calls, instance fields are instantiated again before the constructor code.
订单,反转
new Sandwich(); // prints last
// the instance fields
super(); // new PortableLunch() prints third
super(); // new Lunch() prints second
super(); // new Meal(); prints first
这篇关于Java构造函数 - 继承层次结构中的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!