I was helping a friend with Java the other day, and they were asking about Enums. I explained that the C syntax of (something like)
enumeration Difficulty{
BEGINNER= 1;
PRO=5;
EXPERT = 11;
}
Wasn’t the way to go, the Java syntax is something(1); you made a constructor that accepted an int and then did this and that…etc.
But they stopped me and asked “If we’re using constructors and so on, why bother with an enum, why not just have a new class?”
And I couldn’t answer. So why would you use an enum in this case, and not a class?
Enums are strictly limited. It is impossible to define an enum value outside of the specified values (whereas with a class you can invoke
newto create a new value).Enums are also heavily optimized by at least most JVMs, and there are also new classes and language features which take advantage of enums’ compactness and speed. For example, there are new classes created,
EnumSetandEnumMap, which implement an enum-keyed set or map using a bitset and an array, respectively (which are probably the fastest possible implementations for those abstract data types).Additionally, enum types can be used in
switchstatements. If you’re pre-Java1.7, this is your best option for customizedswitchstatements (and is still probably superior to usingStringvalues because of type safety; mistyping the enum value will cause a compile-time error, but mistyping the string will cause a more insidious runtime error– or worse, a logic error that you can’t understand until you really stare at the code and see the typo).