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));
}
}