Can I set enum start value in Java?

qrtt1 picture qrtt1 · Jul 1, 2009 · Viewed 253.5k times · Source

I use the enum to make a few constants:

enum ids {OPEN, CLOSE};

the OPEN value is zero, but I want it as 100. Is it possible?

Answer

lavinio picture lavinio · Jul 1, 2009

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.