The program below prints:
my name is:null
my name is:null
Someclass static init
AFAIK when a class is first loaded static blocks and fields are always initialized first, instance blocks and fields second. Therefore variables “objectName1” and “objectName2” should be initialized first, instance variable “list” second…but the ouput obviously contradicts this theory… Can anyone explain the program behavior (I’m not looking for a critique of the design in itself btw) ?
import java.util.ArrayList;
import java.util.List;
public class Main2{
public static void main (String[] args){
SomeClass.getInstance();
}
}
class SomeClass {
private static final SomeClass instance = new SomeClass();
public static SomeClass getInstance(){
return instance;
}
static {
System.out.println ("Someclass static init");
}
private static String objectName1 ="test1";
private static String objectName2 ="test2";
@SuppressWarnings("serial")
private List<SomeObject> list=
new ArrayList<SomeObject> () { {
add (new SomeObject(objectName1));
add (new SomeObject(objectName2));
}};
}
class SomeObject {
String name;
SomeObject (String name){
this.name = name;
System.out.println ("my name is:" +name);
}
}
Static blocks are initialized in order (so you can rely on the ones above in the ones below). By creating an instance of
SomeClassas your first static initializer inSomeClass, you’re forcing an instance init during the static init phase.So the logical order of execution of your code is:
SomeClass, all static fields initially defaults (0,null, etc.)SomeClassSomeClassinstance, using current values for static fields (soobjectName1andobjectName2arenull)SomeObjectclass, all static fields initially default (you don’t have any)SomeObjectstatic inits (you don’t have any)SomeObjectusing the passed-innullvaluesSomeClass, settingobjectName1andobjectName2To make this work as you may expect, simply put the inits for
objectName1andobjectName2above the init forinstance.