Tuesday, June 12, 2007

Java 5 Enum

Java 5 enum is a special type of class - subclass of java.lang.Enum. Java compiler transparently translate it. Each symbolic constant of enum is an instance of the class. The constructor must be private to avoid programmatically instantiation. It can also have private attribute and methods.


enum TrafficLight {RED, GREEN, BLUE; }
<=>
public class TrafficLight {
private final String color;
private TrafficLight(String color) { this.color = color; }

public static final TrafficLight GREEN = new TrafficLight(“GREEN”);
...
}

So,on the caller side:

TrafficLight tl = TrafficLight.RED;

Alternatively,

enum TrafficLight {RED("stop"), GREEN("go"), BLUE("warn"); }

where the string is passed in as constructor parameter.

Also, since it is normally inside a file with other class, it cannot be declared as public in that case.

-Some common methods

public enum Shape { RECTANGLE, CIRCLE, LINE }
System.out.println(drawing); // Prints RECTANGLE, toString() will return name
System.out.println(drawing.ordinal()); // Prints 0 for RECTANGLE.
Shape drawing = Shape.valueOf("RECTANGLE"); // convert a string to Enum object

Reference Link

No comments: