class abc {
int a = 0;
static int b;
static abc h = new abc(); //line 4
public abc() {
System.out.println(\"cons\");
}
{
System
JLS says:
The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
Which is exactly your case.
Here is your original example: http://ideone.com/pIevbX - static initializer of abc
goes after static instance of abc
is assigned - so static initializer can't be executed - it's textually after static variable initialization
Let's move line 4 after static initialization block - http://ideone.com/Em7nC1 :
class abc{
int a = 0;
static int b;
public abc() {
System.out.println("cons");
}
{
System.out.println("ini");
}
static {
System.out.println("stat");
}
static abc h = new abc();//former line 4
}
Now you can see the following output:
stat
ini
cons
ini
cons
0
Now initialization order is more like you expected - first called static initializer and then static instance of abc
is initialized in common manner.