Enum idiom

From CSSEMediaWiki
Jump to: navigation, search

Prior to version 1.5, Java had no native support for enumerated types. This led to some nasty practices, and an idiom to avoid the nastiness. In Java 1.5, the idiom has become part of the language.


Old Java enum idiom

Cay Horstmann 2002, p269 gives an idiom for implementing enums in Java.

Common practice

   public static final int SMALL  = 1;
   public static final int MEDIUM = 2;
   public static final int LARGE  = 3;

But this is not very satisfactory, because the compiler can't check type errors. E.g.

   int size = LARGE;

The typesafe enumeration idiom

Make a class to define the enum.

   public class Size {
       private String name;
       public static final Size SMALL  = new Size("SMALL");
       public static final Size MEDIUM = new Size("MEDIUM");
       public static final Size LARGE  = new Size("LARGE");
       private Size(String name) {
           this.name = name;
       public String toString() {
           return name;


  • You don't really need the 'name' String. It is useful for debugging, though.
  • You can add whatever other attributes you like to the class.
  • The constructor is private, so illlegal values can't be created.

The Java 1.5 solution

Java 1.5 has new syntax to support this idiom.

If you have simple needs, it looks like this:

   public enum Size { SMALL, MEDIUM, LARGE }

You can use `Size` like this:

   Size howBig = Size.MEDIUM;

And, (if you know the new Java `for` syntax), like this:

   for (Size s: Size.values())

Under the hood, Java is really creating a new class called `Size`, just like the idiom. This means you can do fancier things, like:

   public enum Size {
       private int diameter;
       public Size(int theDiameter) {
           diameter = theDiameter;
       public void printDiameter() {

As you would expect, we can use our enum like this:

   for (Size s: Size.values())

See also

Personal tools