What's the advantage of a Java enum versus a class with public static final fields?
- Type safety and value safety.
- Guaranteed singleton.
- Ability to define and override methods.
- Ability to use values in
switch
statementcase
statements without qualification. - Built-in sequentialization of values via
ordinal().
- Serialization by name not by value, which offers a degree of future-proofing.
EnumSet
andEnumMap
classes.
Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum
however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf
.
Nobody mentioned the ability to use them in switch
statements; I'll throw that in as well.
This allows arbitrarily complex enums to be used in a clean way without using instanceof
, potentially confusing if
sequences, or non-string/int switching values. The canonical example is a state machine.