Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initialisers?

Tags:

java

static

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

like image 709
Chucky Avatar asked Dec 01 '12 13:12

Chucky


2 Answers

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;
}
like image 155
rekire Avatar answered Oct 02 '22 07:10

rekire


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.

like image 35
Marko Topolnik Avatar answered Oct 02 '22 07:10

Marko Topolnik