As per JLS:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
Also it says,
Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class
I infer two points from this
- Class initialization consists of executing its static initializers
- Class initialization happens if a class is instantiated.
Now,
I assume when I create an object of a class Test in its own (Test's own) static initializer it should throw me a stack overflow as it should call itself repeatedly because as per the above two points, instantiation of the class should initialize the class and initialization block has the instantiation of the class. A stack overflow occurs when I instantiate the class in its own constructor or in its own instance initializers.
For example,
public class Test {
static{
System.out.println("static test");
new Test();
}
{
//new Test(); // This will give a stack overflow
System.out.println("intializer");
}
public Test(){
//new Test(); // This will give a stack overflow
System.out.println("constructor");
}
public static void main(String[] args) {
}
}
However the result is something different.
Result:
static test intializer constructor
Either I am too confused understanding the initialization of the class or I do apologize if I am missing something very obvious here and appreciate your help.