一. 出现背景:
在JDK1.5之前,我们定义常量是这种:public static final String RED = “RED”;
在JDK1.5中增加了枚举类型,我们能够把相关的常量分组到一个枚举类中:
public enum Color {
RED, GREEN, BLUE;
}
使用的时候能够这样:Color c = Color.RED
二. 枚举特点:
1. 枚举enum是一个特殊的Java类。它继承自java.lang.Enum,继承了非常多Enum的方法。但枚举类是一个不能够被继承的final类
2. 枚举类能够定义在interface或class中。当然枚举类型中有构造函数、方法、数据域:
public interface MyConstants {
enum Color {
RED("RED", 1), GREEN("GREEN", 2), BLUE("BLUE", 3);
String desc;
Integer value;
private Color(String desc, Integer value) {
this.desc = desc;
this.value = value;
}
}
enum Light {
RED, GREEN, YELLOW;
}
}
使用:MyConstants.Color.RED
3. 枚举类中的够早