Sunday, March 13, 2005

Typesafe Enums

"Enumeration types are a bit odd, bitfields are odder. The "static" keyword is very strange."
(Dennis Ritchie)

public class Enumerated {
    public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
    
    public static void main(String[] args) {
    }
}

The compiler will implicitly produce a new class Day like this: public static final class Day extends Enum { ...

The compiler will also implicitly produce Day objects members.

        public static final Day MONDAY;
        public static final Day TUESDAY;
        public static final Day WEDNESDAY;
        public static final Day THURSDAY;
        public static final Day FRIDAY;
        public static final Day SATURDAY;
        public static final Day SUNDAY;

Obviously, you should now be able to write code such as:

    public static void main(String[] args) {
        Day day = Day.TUESDAY;
        System.out.println(day);
    }

Since Day extends Enum, you will also be able to use a few methods such as:

    public static void main(String[] args) {
        Day day = Day.TUESDAY;
        System.out.println(day.ordinal());
    }
[user]$ javac Enumerated.java
[user]$ java Enumerated
1

More Examples

public class Enumerated {
    
    public enum Color { RED, GREEN, BLUE }

    public enum TrafficLight { RED, YELLOW, GREEN }
    
    // monday is the first day of the week (ISO-8601)
    public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

    public enum Month { 
        JANUARY, FEBRUARY, MARCH,
        APRIL, MAY, JUNE, 
        JULY, AUGUST, SEPTEMBER,
        OCTOBER, NOVEMBER, DECEMBER
    }
    
    public enum Compass { 
        NORTH, NORTHEAST, EAST, SOUTHEAST, 
        SOUTH, SOUTHWEST, WEST, NORTHWEST
    }

    public enum Planets { 
        MERCURY, VENUS, EARTH, 
        MARS, JUPITER, SATURN, 
        URANUS, NEPTUNE, PLUTO
    }
    
    public enum Piece { EMPTY, PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING }
    
    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    public enum Fish { SALMON, TROUT, TUNA, HADDOCK, SWORDFISH, SHARK }
    
    public enum Gender { MALE, FEMALE }
    
    public static void main(String[] args) {
    }
}

References

Herb Sutter, 2005. The C Family of Languages: Interview with Dennis Ritchie, Bjarne Stroustrup, and James Gosling (http://www.gotw.ca/publications/c_family_interview.htm)

Resources

No comments: