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.. :/
If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.
Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time.
Static variables can be assigned as many times as you wish. static int count = 0; is initialization and that happens only once, no matter how many times you call demo .
Because statics are initialized in the order they are given in source code.
Check this out:
class MyClass { private static MyClass myClass = new MyClass(); private static MyClass myClass2 = new MyClass(); public MyClass() { System.out.println(myClass); System.out.println(myClass2); } }
That will print:
null null myClassObject null
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With