Using Type-Safe Enums
Example 5.24 illustrates using enum constants. An enum type is essentially used as any other reference type, and the restrictions are noted later in this section. Enum constants are actually final, static variables of the enum type, and they are implicitly initialized with instances of the enum type when the enum type is loaded at runtime. Since the enum constants are static members, they can be accessed using the name of the enum type—analogous to accessing static members in a class.
Example 5.24 shows a machine client that uses a machine whose state is an enum constant. In this example, we see that an enum constant can be passed as an argument, as shown at (1), and we can declare references whose type is an enum type, as shown at (3), but we cannot create new constants (i.e., objects) of the enum type MachineState. An attempt to do so at (5) results in a compile-time error.
The text representation of an enum constant is its name, as shown at (4). Note that it is not possible to pass a value of a type other than a MachineState enum constant in the call to the method setState() of the Machine class, as shown at (2).
Example 5.24 Using Enums
// File: MachineState.java
public enum MachineState { BUSY, IDLE, BLOCKED }
// File: Machine.java
public class Machine {
private MachineState state;
public void setState(MachineState state) { this.state = state; }
public MachineState getState() { return this.state; }
}
// File: MachineClient.java
public class MachineClient {
public static void main(String[] args) {
Machine machine = new Machine();
machine.setState(MachineState.IDLE); // (1) Passed as a value.
// machine.setState(1); // (2) Compile error!
MachineState state = machine.getState(); // (3) Declaring a reference.
System.out.println(
“Current machine state: ” + state // (4) Printing the enum name.
);
// MachineState newState = new MachineState(); // (5) Compile error!
System.out.println(“All machine states:”);
for (MachineState ms : MachineState.values()) { // (6) Traversing over enum
System.out.println(ms + “:” + ms.ordinal()); // contants.
}
System.out.println(“Comparison:”);
MachineState state1 = MachineState.BUSY;
MachineState state2 = state1;
MachineState state3 = MachineState.BLOCKED;
System.out.println(state1 + ” == ” + state2 + “: ” +
(state1 == state2)); // (7)
System.out.println(state1 + ” is equal to ” + state2 + “: ” +
(state1.equals(state2))); // (8)
System.out.println(state1 + ” is less than ” + state3 + “: ” +
(state1.compareTo(state3) < 0)); // (9)
}
}
Output from the program:
Click here to view code image Current machine state: IDLE
All machine states:
BUSY:0
IDLE:1
BLOCKED:2
Comparison:
BUSY == BUSY: true
BUSY is equal to BUSY: true
BUSY is less than BLOCKED: true
Leave a Reply