Monday, April 14, 2008

Working with Enumerations in Java

An enumeration type is a Java type, which all values for the type are known when the type is defined. It is a special kind of class, with an instance that represents each value of the enumeration.

An instance of the enum class is called an enum constant, we will be referring to this term along the article.

There are some interesting things a developer must know when working with enums:

  • When declaring an enumeration, it is like declaring a class but with two exceptions:
    - The keyword enum is used instead of class,
    - Before declaring any class members, an enum must declare first all its enum constants.

  • All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.

  • All enum are implicitly Serializable and Comparable.

  • Enums can have fields, methods and nested types, including nested enums.

  • Two static methods are automatically generated by the compiler:
    - values: returns an array of the enum constansts
    - valueOf(String name): returns the enum constant for a given name.

  • An enum type is not allowed to override the finalize method from Object.

  • Enum instances may never be finalized.

  • Nested enums can have any access modifier, while a top-level enum is public or package accessible.

  • Enums are implicitly static.

  • An enum cannot be declared abstract, but can declare abstract methods. Also, it cannot be declared final.

  • An enum constant declaration cannot have modifiers applied to it, except for annotations.

  • Restrictions of enum constructors:
    - All enum constructors are private.
    - An enum constructor cannot explicitly invoke a superclass constructor.
    - An enum constructor cannot use a non-constant static field of the enum.

  • Enum constants can have constant-specific behavior.

  • Some useful properties are set for enums:
    - The method clone is overriden to be declared final and to throw CloneNotSupported Exception.
    - The hasCode and equals method are overriden to be declared final.
    - The compareTo method is implemented and defined so that enum constants have a natural ordering based on their order of declaration (the first declared enum constant has the lowest position in the ordering).

  • The toString method returns the name of the enum constant.

When using an enum will depend on how sophisticated is the behavior of type, because if the behavior is too sophisticated, it is more likely the application might need to specialize that behavior. Enums are suggested for simple types like card suits or the days of the week.