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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…