I’m looking at this code of the correct way to do a singleton in java: What is an efficient way to implement a singleton pattern in Java?
I’m a little confused, how do you add a method to a enumeration?
public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
And the enumeration in the code above, doesn’t even make sense to me, you have the symbol:
INSTANCE;
how is that a correct line?
I’m coming from c#, and this syntax got me curious and I’m hoping someone can explain or make sense of the above.
I guess it means java has a more purer idea of an enumeration as it can have behaviour?
An enum in Java is actually a class. One that implicitly extends java.lang.Enum. The special syntax you see at
INSTANCE;is a declaration of an enum constant. This is going to be used to make an instance of your enum class which can be referred to in code. As a matter of fact, you can even have a non-default constructor for your enum and use it in the constant declaration. Example:Treating enums as true objects has certain advantages. Putting some logic into enums is convenient, but shouldn’t be abused either. The singleton pattern via enums is a nice solution in my opinion, though.