In Java we can do the following to initialize class and call method inside that class:
public class MyClass {
public String myClassMethod() {
return \"
It's a simple implementation of the Singleton pattern, relying on the mechanisms of how Enum's work.
If you use MyEnumClass.INSTANCE
a second time, you'll get the same object instance.
In contrast, new MyClass();
will create a new object.
See also discussion here:
What is the best approach for using an Enum as a singleton in Java?
There would possibly be more to learn by reading Java Language Spec Section 8-9
An enum
is essentially a singleton pattern.
The JVM handles the initialization and storage of enum
instances. To see this most clearly you can write:
public enum MyEnumClass {
INSTANCE("some value for the string.");
private final String someString;
private MyEnumClass(final String someString) {
this.someString = someString;
}
public String getSomeString(){
return someString;
}
}
And in another class:
public static void main(String[] args) {
final MyEnumClass myEnumClass = MyEnumClass.INSTANCE;
system.out.println(myEnumClass.getSomeString());
}
This would print out "some value for the string.".
This demonstrates that the enum
instances are initialised at class load time, i.e. as if by the static
initialiser.
Or put another way:
new MyClass() == new MyClass();
Is always false
, whereas:
MyEnumClass.INSTANCE == MyEnumClass.INSTANCE;
Is always true
. i.e. MyEnumClass.INSTANCE
is always the same MyEnumClass.INSTANCE
whereas a new MyClass
is created every time your call new MyClass()
.
This brings us nicely to your question of "better".
An enum
is a singleton instance with various nifty methods for converting String
enum
names into a reference to the singleton instance that it represents. It also guarantees that if you de-serialize an enum
there won't be two separate instances like there would for a normal class.
So an enum
is certainly much better as a robust and threadsafe singleton than a class
.
But we cannot have two instances of INSTANCE
with the different values for someString
so the enum
is useless as a class
...
In short enum
s are good for what they're good for and class
es are good for what they're good for. They are not substitutes and therefore cannot be compared in any meaningful way expect when one is used as the other.