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:
- Initialize member fields of the base class(es)
- Run the base class(es) constructor(s)
- Initialize member fields of sub class
- Run the constructor of sub class
And my understanding of execution of static initializer is
- the static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.
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