Here is a quick primer on Java enums:
- Enumeration is fixed set of constants
- Provides type-safe representation of constant data
- enum is the Java class that represents enumeration
- enum cannot extend any other class
- Constants in enum are public,final, and static
- enum can declare additional methods and fields
- enum can declare any number of constructors
- values() returns array of enum values
- If you need int value, you can use ordinal() static method
- static valueOf() method can be used to convert a string into corresponding enum
- enum can be used in switch statement
Here is an example of enum with constructors:
public enum IceCream {
PLAIN(2),
SUGAR(3),
WAFFLE(5);
private IceCream(int scoops) {
this.scoops = scoops;
}
public final int scoops;
}
public class TestEnum {
/**
* @param args
*/
public static void main(String[] args) {
IceCream cone1 = IceCream.PLAIN;
IceCream cone2 = IceCream.SUGAR;
IceCream cone3 = IceCream.WAFFLE;
System.out.println("cone 1 needs " + cone1.scoops + " scoops");
System.out.println("cone 2 needs " + cone2.scoops + " scoops");
System.out.println("cone 3 needs " + cone3.scoops + " scoops");
}
}
Output:
cone 1 needs 2 scoops
cone 2 needs 3 scoops
cone 3 needs 5 scoops
Nice intro for enum.