I have 2 classes:
Class A:
public class A {
static B b = new B();
static {
System.out.println("A static block");
}
public A() {
System.out.println("A constructor");
}
}
Class B:
public class B {
static {
System.out.println("B static block");
new A();
}
public B() {
System.out.println("B constructor");
}
}
I create a Main class which just creates new A:
public class Main {
public static void main(String[] args) {
new A();
}
}
The output I get is:
B static block
A constructor
B constructor
A static block
A constructor
As you can see, the constructor of A is invoked before its static initializer.
I understand it got something to do with the cyclic dependency I created but I was under the impression the static initializer should always run before the constructor.
What is the reason for this to happen (technically in the java implementation) ?
Is it recommended to avoid static initializers all together ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…