英文:
Questioning the order in which the code is executed
问题
我发现了这段代码(https://stackoverflow.com/questions/25340310/java-constructor-does-not-explicitly-invoke-a-superclass-constructor-java-doe)...
输出结果是:a2 a1 b2 b3 b1 c1 a2 a1 b2 b3 b1 c1 c2
我预期输出应该只有 c1 c2,但是我无法理解代码执行的顺序。
我希望有一个详细的解释,只是为了确保我足够清楚地理解事情。谢谢!
英文:
So I stumbled across this piece of code (https://stackoverflow.com/questions/25340310/java-constructor-does-not-explicitly-invoke-a-superclass-constructor-java-doe)...
public class App {
public static void main(String[] args){
new C();
new C(1.0);
}
}
class A {
public A(){
this(5);
System.out.println("a1");
}
public A(int x){
System.out.println("a2");
}
}
class B extends A {
public B(){
this(false);
System.out.println("b1");
}
public B(int x){
super();
System.out.println("b2");
}
public B(boolean b){
this(2);
System.out.println("b3");
}
}
class C extends B {
public C(){
System.out.println("c1");
}
public C(double x){
this();
System.out.println("c2");
}
}
And the output that I got is a2 a1 b2 b3 b1 c1 a2 a1 b2 b3 b1 c1 c2
I was expecting it to be c1 c2 only but I just cannot wrap my head around the sequence in which the code is executed.
I would love a detailed explanation, just to make sure I understand things clearly enough. Thank you!
答案1
得分: 1
继承类在构造函数的开始处隐式调用super()
。
因此,执行顺序如下:
C()
--> B()
--> A()
--> A(5)
--> print('a2')
--> print('a1')
--> B(false)
--> B(2)
--> print('b2')
--> print('b3')
--> print('b1')
--> print('c1')
(这完成了对C()
的第一次调用)
C(1.0)
--> 对于a2, a1, b2, b3, b1, c1,执行完全相同的轨迹,最后执行print('c2')
来完成函数。
英文:
Inheriting classes call super()
implicitely at the beginning of the constructor.
Thus, the execution is as follows:
C()
--> B()
--> A()
--> A(5)
--> print('a2')
--> print('a1')
--> B(false)
--> B(2)
--> print('b2')
--> print('b3')
--> print('b1')
--> print('c1')
(this finishes the very first call to C()
)
C(1.0)
--> does the exact same trajectory for a2, a1, b2, b3, b1, c1, and then finally print('c2')
to finish the function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论