SE450: Type Safe Enum [2/24] ![]() ![]() ![]() |
An enumerated type is used to hold a fixed set of constants, and name them in a fashion to make your code more readable and maintainable.
Java doesn't have an enum type like C - thankfully! They were just integer constants, and were not typesafe.
Programmers usually get around this by creating a number
of public final static int variables in an interface
or class and using them to enumerate types. This can be problematic.
For example, you could make a Card enum for a card game
public class Card {
public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;
}
Problems:
To do this, use a typesafe enum pattern (example from Bloch's Effective Java), go here for some from the book.
public class Suit {
private final String name;
// can't be created elsewhere!
private Suit(String name) { this.name = name; }
public String toString() { return name; }
public static final Suit CLUBS = new Suit("clubs");
public static final Suit DIAMONDS = new Suit("diamonds");
public static final Suit SPADES = new Suit("spades");
public static final Suit HEARTS = new Suit("hearts");
}
You can also provide ordering using an ordinal to assign ordering to the objects as they are created as well.
Since the enum is a full blown class, it can do anything a class can, and be much more effective than the old enumerated type - see the book and Bloch's Effective Java for more examples.