This is another feature introduced in Java 1.5. It solves the problem of enumerated types in Java.
Previously you would write code –
[sourcecode language=”java”] public class TrafficLights { public static final String RED = "0";
public static final String AMBER = "1";
public static final String GREEN = "2";
}
[/sourcecode]
This can now be written as –
[sourcecode language=”java”] enum TrafficLights {The advantages being –
The enum itself is a special class, and as such it can have the following –
private int id;
private TrafficLights(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
[/sourcecode]
enum TrafficLights implements WhatsMyColourInterface {
RED(0), AMBER(1), GREEN(2);
private String id;
private TrafficLights(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void getMyColour() {
System.out.println("My Colour is – " + name());
}
}
[/sourcecode]
In Action
Here is a real world example from Oracles Website (http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html) –
[sourcecode language=”java”] public enum Planet { private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
public double surfaceGravity() {
return G * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}
public static void main(String[] args) {
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass));
}
}
[/sourcecode]
Output –
[sourcecode language=”java”]
$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
Your weight on PLUTO is 11.703031
[/sourcecode]