我们常常会需要int全局常量 如下:
public static final int APP_START=1;
public static final int APP_PAUSE=0;
public static final int APP_STOP =2;
public static final int PLAY_START=1;
public static final int PLAY_PAUSE=0;
public static final int PLAY_STOP =2;
这种方法叫作int枚举模式,存在很多不足,但是经常被我们这样写。采用int 枚举是编译时常量,,如果与int常量相关的值发生变化,客户端只有通过再次编译,才会有效果。
怎么避免这种缺陷呢,在java1.5开始,提供了enum枚举方案:
public enum APP { START ,STOP ,PAUSE};
public enum PLAY{ START ,STOP ,PAUSE};
枚举提供了编译时的类型安全,如果声明一个参数类型为App,就可以保证,被传到该参数上的任何非空对象一定属于有效的app 3个属性之一,不会引用到play的属性。
包名同名的常量的多个枚举可以在一个系统中和平共处。因为每个类型都有自己的命名空间比如app.start与play.start没有任何冲突。
枚举类型还允许添加任意的方法和域。可以利用适当的方法增强枚举类型,也可以作为枚举常量的集合,随着时间的推移成为全功能的抽象。
枚举用起来其实和一般类没什么区别,只是它不能被继承,它也可以有方法和域。
public enum Planet {
MERCURY(3.302e+23, 2.439e6),
VENUS(4.869e+24, 6.052e6),
EARTH(5.975e+24, 6.378e6),
MARS(6.419e+23, 3.393e6),
JUPITER(1.899e+27, 7.149e7),
SATURN(5.685e+26, 6.027e7),
URANUS(8.683e+25, 2.556e7),
NEPTUNE(1.024e+26, 2.477e7);
private final double mass;
private final double radius;
private final double surfaceGravity;
private static final double G = 6.67300e-11;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
surfaceGravity = G * mass / (radius * radius);
}
public double mass() {
return mass;
}
public double radius() {
return radius;
}
public double surfaceGravity() {
return surfaceGravity;
}
public double surfaceWeight(double mass) {//F=ma
return mass * surfaceGravity;
}
}
public static void main(String[] args) {
double x = 2.0;
double y = 4.0;
for(Operation op : Operation.values())
System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x,y));
}
总之,与int 常量相比,枚举类型的优势不言而喻,枚举类型易读得多,也更加安全,更加强大。