I'm trying to discover the order in which initialization occurs, or rather the reason behind why initialization occurs in this order. Given the code:
public class Main {
{
System.out.printf("NON-STATIC BLOCK\n");
}
static{
System.out.printf("STATIC BLOCK\n");
}
public static Main m = new Main();
public Main(){
System.out.printf("MAIN CONSTRUCTOR\n");
}
public static void main(String... args) {
//Main m = new Main();
System.out.printf("MAIN METHOD\n");
}
}
Output:
STATIC BLOCK
NON-STATIC BLOCK
MAIN CONSTRUCTOR
MAIN METHOD
However, moving m
's declaration before the initialization block produces:
NON-STATIC BLOCK
MAIN CONSTRUCTOR
STATIC BLOCK
MAIN METHOD
and I have absolutely no idea why it occurs in this order. Furthermore, if I eliminate the static
keyword in the declaration of m
, neither the init block nor the constructor fire. Can anyone help me out with this?