What is the difference between:
private static Object myVar = new Object();
And:
private static Object myVar2;
static{
myVar2 = new Object();
}
In both case i end up with an initilized static variable
You can use better the second one if the initialisation of your static and maybe also final object is more complex.
E.g.:
static final MyClass something;
static {
Config conf=SettingsManager.getSettings();
MyClass obj=MyClassFactory.getInstance(conf);
obj.setVodoo(true);
something=obj;
}
In your example there is no difference and the compiled bytecode will end up exactly or very nearly the same. Static initializers are sometimes useful, but more often misused. If the goal is to populate a single static field, write a static method that returns the initialized object and call that method inside the static field declaration.
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