enum
An enum is a language construct that allows you to create a type
with a finite list of possible values, kind of like choosing from
a menu.
| Direction.java |
| 1 | public enum Direction { |
| 2 | NORTH, SOUTH, EAST, WEST |
| 3 | } |
$ javac Direction.java
|
The next example shows you how you can use enums. They
are types that can be compared with == or !=. They have
string representations that are the same as their declared
name.
| UseDirection.java |
| 1 | public class UseDirection { |
| 2 | public static void main(String[] args) { |
| 3 | Direction d1 = Direction.EAST; |
| 4 | Direction d2 = Direction.SOUTH; |
| 5 | if(d1 == d2) |
| 6 | System.out.println("equal!"); |
| 7 | else |
| 8 | System.out.println(d1+" is not equal to "+d2); |
| 9 | } |
| 10 | } |
$ javac UseDirection.java
| $ java UseDirection
EAST is not equal to SOUTH
|
If you want to store additional information in an enum, you
can.
| ExDirection.java |
| 1 | public enum ExDirection { |
| 2 | // provide values with constructors, put semicolon at the end |
| 3 | NORTH(1,0), SOUTH(-1,0), EAST(0,1), WEST(0,-1); |
| 4 | |
| 5 | // define fields |
| 6 | public final int deltaX,deltaY; |
| 7 | |
| 8 | // define constructors |
| 9 | ExDirection(int dx,int dy) { |
| 10 | deltaX = dx; |
| 11 | deltaY = dy; |
| 12 | } |
| 13 | } |
$ javac ExDirection.java
|
|