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
ii)class B is getting loaded , so the second static block gets called , and it prints B
iii)default constructor of A (because new B is requested) so it prints a
iv) and finally default constructor of B as it was requested with new B()
so it prints b , the output is ABab
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.