Use enumerated constants in Java

In the article “Create enumerated constants in Java” , Eric point out static final constants like this:

static final int YELLOW = 0;
static final int GREEN = 1;
static final int BLUE = 2;

had the following drawbacks:

  • The major drawback is the lack of type safety. Any integer that is calculated or read in can be used
  • Another drawback is the lack of a readable identifier. If you use a message box or console output to display the current color choice, you get a number. That makes debugging pretty difficult

And enumerated constants had the following advantages:

  • Type safe
  • Printable
  • Ordered, for use as an index
  • Linked, for looping forwards or backwards
  • Enumerable

He also showed how to create enumerated constants in Java in the old version like JDK 1.1. But the “enum” keyword in Java 5 had taken care of all of that.

Based on this article, Java 1.5 make it very easy to create enumerated constants. The keyword “enum” is a new and the only new one brought into the language in JDK 1.5. You just need a simple one line definition like this:

public enum breakfast {yellow, green, blue };

Here is the official document from Sun.

The following is a simple enumerated constants class show that you can actually add properties and behavior to it:

public enum MsgStatusConsts {
    Received    (0),
    Finished    (1),
    Processing  (2),
    Error       (-1),
    Discard     (-2);

    private final int code;    //status code
    private MsgStatusConsts(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static void main(String args[]) {
        for (MsgStatusConsts msc : MsgStatusConsts.values()) {
            System.out.printf("The code for %s is %d, string %s%n",
                msc, msc.getCode(), msc.toString());
        }
        System.out.printf("What is valueOf(Error) %s, code %d%n",
            MsgStatusConsts.valueOf("Error"),
            MsgStatusConsts.valueOf("Error").getCode());
    }
}

Eric Armstrong (1997). Create enumerated constants in Java http://www.javaworld.com/jw-07-1997/jw-07-enumerated.html

~ by yingliang on September 24, 2009.

Leave a Reply




*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image