Java 枚举
在 jdk1.5 以前,定义常量:
public class Status{
public final static int WAIT= 0;
public final static int ACTIVE= 1;
}
在 jdk1.5 以后,可以使用枚举来定义常量,每个常量都是一个类,默认私有的构造函数,所以也适合用来创建单例:
public enum Status{
WAIT, ACTIVE
}
1,可以使用在 switch 中使用:
public static void main(String[] args) {
Status s = Status.WAIT;
switch (s) {
case WAIT:
System.out.println("wait");
break;
case ACTIVE:
System.out.println("active");
break;
}
}
2,与普通类一样,可以定义构造函数(必须且默认是私有的)、属性、方法,可以实现接口,但不能再继承其他类,因为已经继承了 enum 类:
public enum Status{
//枚举类必须写在最前面
WAIT(0), ACTIVE(1);
private int type;
Status(int i) {
this.type = i;
}
@Override
public String toString() {
return String.valueOf(type);
}
}
3,实现抽象方法的枚举类:
public enum Status{
WAIT(0){
@Override
public Status nextStatus() {
return ACTIVE;
}
},
ACTIVE(1){
@Override
public Status nextStatus() {
return WAIT;
}
};
private int time;
Status(int time) {
this.time = time;
}
public abstract Status nextStatus();
}

浙公网安备 33010602011771号