Until Java 5 numeric constants were often used to mean different states of something. Eg,
final static int OFF = -1;
final static int RUNNING = 0;
final static int STANDBY = 1;
final static int HIBERNATING = 2;
This easily causes errors by allowing wrong values. How is the compiler to know that wherever these values are acceptable a value of 3 would be wrong?
There are other problems with this approach too. For example if the value is printed out it is just a number, without meaning unless a switch statement is used to convert each value to a String. Then how could we ensure that the Strings matched the right values?
Java 5 solves the problem by introducing a new type - enum
. Like boolean
, you don't know any numeric values; the compiler keeps those to itself. This approach also provides a namespace for the values, to avoid conflicts. An enum
really defines a class. Eg, instead of what we had above, we would now write
enum ActivityState {OFF, RUNNING, STANDBY, HIBERNATING};
then declare variables of this new class and perhaps initialise them:
ActivityState state = ActivityState.OFF;
There is a backing class, java.lang.Enum<E>
(see the API documentation). Like every other class this is descended from Object and so it inherits a toString ()
method. This is overridden in such a way that the String it returns is in fact the name given in the source code. So after the initialisation above, System.out.print (state);
yields "OFF"
.