Skip to content
Joel Gallant edited this page Jun 19, 2013 · 1 revision

Creating an Enum

Enums are type-safe, instance-safe and compare-safe. They are type-safe in that elements will only match other enum values of the same type. They are instance-safe in that the only enum values will be the ones your create inside of the class. They are compare-safe in that equals(Object o) will only return true when the two are the same value in the enum.

Since enums are not available in Java 1.4 ME, the Enum class fills it's roll. Although it isn't quite as robust or safe (exploits can reveal internals), it works well in the absence of anything official.

This is what an enum should look like:

public final class Colour extends Enum {

    public static final Colour RED = new Colour("RED");
    public static final Colour BLUE = new Colour("BLUE");
    public static final Colour YELLOW = new Colour("YELLOW");
    public static final Colour ORANGE = new Colour("ORANGE");

    private Colour(String name) {
        super(name);
    }
}

or, if you do not need names for toString()

public final class Colour extends Enum {

    public static final Colour RED = new Colour();
    public static final Colour BLUE = new Colour();
    public static final Colour YELLOW = new Colour();
    public static final Colour ORANGE = new Colour();

    private Colour() {
        super();
    }
}

Usage of Enums

http://en.wikipedia.org/wiki/Enumerated_type

Clone this wiki locally