枚举使用enum
定义,默认继承java.lang.Enum,不再继承Object
枚举中必须在第一行列出所有实例,枚举的构造器未接收形参的情况下,实例可以不写括号()
1 2 3 4 5 6 7 8 9 10
|
public enum Direction{ North, South, East, West;
Direction() {
} }
|
当然,如果你想写括号也可以写
1 2 3 4 5 6 7
| public enum Direction{ North(), South(), East(), West();
Direction() {
} }
|
不过当构造器接收了参数的时候,则一定要在第一行列出的实例中传入对应参数
1 2 3 4 5 6 7 8 9 10
|
public enum Direction{ North(""), South(""), East(""), West("");
Direction(String s) { } }
|
实际上,上述枚举类等同于如下
1 2 3 4 5 6 7 8 9 10
| public class Direction{ public static final Direction North = new Direction(""); public static final Direction South = new Direction(""); public static final Direction East = new Direction(""); public static final Direction West = new Direction(""); private Direction(String s) { } }
|
在使用上,也大同小异
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public static void main(String[] args) { check(Direction.North); check(Direction.South); }
private static void check(Direction direction) { if (direction == Direction.North) { System.out.println("North"); } else if (direction == Direction.South) { System.out.println("South"); } }
public enum Direction{ North, South, East, West; }
|
用switch
更为便捷
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public static void main(String[] args) { check(Direction.North); check(Direction.South); }
private static void check(Direction direction) { switch (direction) { case North: System.out.println("North"); break; case South: System.out.println("South"); break; } }
public enum Direction{ North, South, East, West; }
|