Look at the following code:
public class Foo {
private static Foo sigleton=new Foo();
private static int count1;
private static int count2=0;
private Foo (){
count1++;
count2++;
}
public static Foo getInstance(){
return sigleton;
}
public static void main(String[] args) {
//Foo f= Foo.getInstance(); // case 1
//Foo f= new Foo(); // case 2
System.out.println(f.count1);
System.out.println(f.count2);
}
}
For each run, uncomment one of the lines in the main method.
Why is the output in case 1 and 2 different?
Simply because in the first case, one
Fooobject is constructed, but in the second case, twoFooobjects are constructed.You initialise the
sigletonfield statically – so when the class is loaded, theFooconstructor is always called (as you specified for the field initialiser).Now in case 1, you’re just calling a method, which returns the
sigletonobject which has already been constructed – so no further constructors are called. In case 2, you explicitly construct a newFooobject – but thesigletonwill still be constructed. Hence in this latter case, two objects are created, the constructor is run twice in total, and socount1andcount2will be one greater.