Advantages of Java's enum over the old "Typesafe Enum" pattern?

design-patterns, enums, java, language-design

Solution

- "cannot be subclassed" isn't a restriction. It's one of the big advantages: It ensures there there is always only ever exactly the set of values defined in the `enum` and no more!

- `enum` correctly handles serialization. You can do that with type-safe enums as well, but it's often forgotten (or simply not known). This ensures that `e1.equals(e2)` always implies `e1 == e2` for any two `enum` values `e1` and `e2` (and vice versa, which is probably more important).

- There are specific lightweight data structures that handle enums: `EnumSet` and `EnumMap` (stolen from this answer)

Problem

In Java prior to JDK1.5, the "Typesafe Enum" pattern was the usual way to implement a type that can only take a finite number of values: ``` public class Suit { private final String name; public static final Suit CLUBS =new Suit("clubs"); public static final Suit DIAMONDS =new Suit("diamonds"); public static final Suit HEARTS =new Suit("hearts"); public static final Suit SPADES =new Suit("spades"); private Suit(String name){ this.name =name; } public String toString(){ return name; } } ``` (see e.g. Item 21 from Bloch's Effective Java). Now in JDK1.5+, the "official" way is obviously to use `enum`: ``` public enum Suit { CLUBS("clubs"), DIAMONDS("diamonds"), HEARTS("hearts"), SPADES("spades"); private final String name; private Suit(String name) { this.name = name; } } ``` Obviously, the syntax is a bit nicer and more concise (no need to explicitly define fields for the values, suitable `toString()` provided), but so far `enum` looks very much like the Typesafe Enum pattern. Other differences I am aware of: - enums automatically provide a `values()` method - enums can be used in `switch()` (and the compiler even checks that you don't forget a value) But this all looks like little more than syntactic sugar, with even a few limitations thrown in (e.g. `enum` always inherits from `java.lang.Enum`, and cannot be subclassed). Are there other, more fundamental benefits that `enum` provides that could not be realized with the Typesafe Enum pattern?

Original source

Related problems