Clicky

ChrisEllsworth.com

The online home of Christopher Chess Ellsworth
Welcome to ChrisEllsworth.com Sign in | Join | Help
in Search

Chris's Development Blog

Tutorials and thoughts on software development.

Enumerations in Java 1.5

Here is a simple example of the new enumeration features in Java 1.5. The Java compiler translates enumerations into regular classes that inherit from the Enum class. This means that you define enumerations the same way as you define classes, with the exception that you use the enum keyword instead of class.

Remeber, enumerations are Objects, and inherit from Enum, so be sure to read the javadocs.

EnumExample.java

public class EnumExample {

    // Inner enum "class"
    public enum Coin {
        penny(1), nickel(5), dime(10), quarter(25);

        Coin(int value) { this.value = value; }

        private final int value;
        public int value() { return value; }
    }

    private enum CoinColor { copper, nickel, silver }

    private static CoinColor color(Coin c) {
        switch(c) {
          case penny:   return CoinColor.copper;
          case nickel:  return CoinColor.nickel;
          case dime:
          case quarter: return CoinColor.silver;
          default: throw new AssertionError("Unknown coin: " + c);
        }
    }
   
    public static void main(String[] args) {
        System.out.println("Starting...");
        System.out.println(Coin.valueOf("penny").value());
        for (Coin c : Coin.values())
            System.out.println(c + ":   \t" + c.value() +" \t" + color(c));
    }

}

 

Published Monday, January 24, 2005 7:01 PM by Christopher Chess Ellsworth
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

Locations of Visitors

Locations of visitors to this page
©2007 Christopher Chess Ellsworth