[英]What is the order of execution when static initializer and inheritance is involved in JAVA?
I ran across this code: 我遇到了以下代码:
public class A {
static{
System.out.print("A");
}
A(){
System.out.print("a");
}
}
public class B extends A {
static{
System.out.print("B");
}
B(){
System.out.print("b");
}
}
public class Test {
public static void main(String[] args) {
new B();
}
}
My understanding of order of object construction is: 我对对象构造顺序的理解是:
And my understanding of execution of static initializer is 我对静态初始化程序的执行的理解是
But I can not come up with the correct printing, i got: 但是我无法提出正确的打印,我得到了:
A(base initialzer)
a(base constructor)
B(subclass initialize)
b(subclass constructor)
Could someone explain what is the correct order and why? 有人可以解释正确的顺序是什么,为什么?
Update 更新资料
static blocks will called whenever the class is loaded by the classloader , thus the correct order is : 当类加载器加载类时,将调用静态块,因此正确的顺序是:
i) class A is loaded (because B extends A
is requested) so the first static block is called , and it prints A i)加载了类A(因为请求了
B extends A
),所以第一个静态块被调用,并输出A
ii)class B is getting loaded , so the second static block gets called , and it prints B ii)正在加载类B,因此调用了第二个静态块,并输出B
iii)default constructor of A (because new B is requested) so it prints a iii)A的默认构造函数(因为需要新的B),因此它会打印a
iv) and finally default constructor of B as it was requested with new B()
so it prints b , the output is ABab iv)最后是
new B()
请求的B的默认构造函数,因此它输出b,输出为ABab
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.