The following code prints null once.
class MyClass {
private static MyClass myClass = new MyClass();
private static final Object obj = new Object();
public MyClass() {
System.out.println(obj);
}
public static void main(String[] args) {}
}
Why are the static objects not initialized before the constructor runs?
Update
I’d just copied this example program without attention, I thought we were talking about 2 Object fields, now I saw that the first is a MyClass field.. :/
Because statics are initialized in the order they are given in source code.
Check this out:
That will print:
EDIT
Ok let’s draw this out to be a bit more clear.
Is that clear?
EDIT 2
As Varman pointed out the reference to itself will be null while it is being initialized. Which makes sense if you think about it.