I am trying to understand initialization order of Java class. Specifically when and in what order are static and Instance initializer/fields are executed. I came up with example as in this stackoverflow Question. Why does adding static to the self constructor invocation stop the code from going into recursion.
public class Test {
public static void main(String a[]) {
Cons1 c1 = new Cons1();
}
}
class Cons1 {
static Cons1 c = new Cons1(); /* if static is removed then recursion
occurs */
Cons1() {
//does something
}
}
Is there any specific reason for this difference in behavior between static and instance context. I went through the Java doc Detailed Initialization Procedure, but unable to understand what is the logic behind such behavior. Any explanation or reference to JLS specs will be helpful.
PS : I have gone through this Similar stackoverflow post, However I cannot get my answer from there.