I have read that it is possible to implement Singleton
in Java using an Enum
such as:
public enum MySingleton {
INSTANCE;
}
But, how does the above work? Specifically, an Object
has to be instantiated. Here, how is MySingleton
being instantiated? Who is doing new MySingleton()
?
This,
public enum MySingleton {
INSTANCE;
}
has an implicit empty constructor. Make it explicit instead,
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
If you then added another class with a main()
method like
public static void main(String[] args) {
System.out.println(MySingleton.INSTANCE);
}
You would see
Here
INSTANCE
enum
fields are compile time constants, but they are instances of their enum
type. And, they're constructed when the enum type is referenced for the first time.