Simple Singleton Using ENUM

MySingleton.java

public enum MySingleton {
  INSTANCE;   
}

Enum Classes has Private Constructor by Default

The Above code can be explicitly written as

MySingleton.java

public enum MySingleton {
    public final static MySingleton INSTANCE = new MySingleton();
    private MySingleton() {
    }
}

When your code first accesses INSTANCE, the class MySingleton will be loaded and initialized by the JVM. This process initializes the static field above once (lazily).

Why cant enum constructors be protected or public in Java?
Enums as a class with a finite number of instances. There can never be any different instances beside the ones you initially declare.Thus, you cannot have a public or protected constructor, because that would allow more instances to be created.

Comments are closed.