I know there are lot of questions on Singleton pattern. But here what I would like to know about the output which might also cover how “static” works in Java.
public class Singleton {
private static Singleton currentSingleton = new Singleton();
public static Singleton getSingleton() {
return currentSingleton;
}
private Singleton() {
System.out.println("Singleton private constructor...");
}
public static void main(String[] args) {
System.out.println("Main method...");
}
}
This is the output from running the code…
Singleton private constructor…
Main method…
When I debugged this code, control went first to line
System.out.println("Singleton private constructor...") and prints.
(private static variable currentSingleton is still null at this point)
Then it goes to line
private static Singleton currentSingleton = new Singleton();
and then initializes the private variable.
Then at last, it goes to main() method and prints.
My Questions are:
- Why it first prints “Singleton private constructor…” which is in private constructor.
I thought control should first go to main() method since it is the entry point. Also I am not creating any instance anywhere (except in variable initialization). - Later it goes to static variable instantiation line (currentSingleton=null at this point)
private static Singleton currentSingleton = new Singleton();
Though currentSingleton gets a value here, why constructor is not called again?
Mainly I want to know the flow of control of this program.
You cannot invoke the main method in the class until it has been properly initialized (i.e. static fields and static blocks have been evaluated). When it is initialized, an instance of your singleton is created by invoking the private constructor. Later the main method is invoked.
The class in question has a static field to which you assing a value. Since the field is static it must be initialized before the class can be used in any context, that is, it must receive a value. In this case its value happens to be an instance of the same class. This is what triggers your private costructor during class initialization.
If you want to delve into the process and understand it better please refer to the Java Laguage Specification. More specifically in the section12.4 Initialization of Classes and Interfaces you will find further details.