1.枚举像普通的类一样可以添加属性和方法,可以为它添加静态和非静态的属性或方法;注:枚举写在最前面,否则编译出错
public enum Week {
Sun, Mon , Tue , Wed , Thu , Fri , Sat;
}
2.实现带有构造器的枚举
//通过括号赋值,而且必须带有一个参构造器和一个属性跟方法,否则编译出错
//赋值必须都赋值或都不赋值,不能一部分赋值一部分不赋值;如果不赋值则不能写构造器,赋值编译也出错
public enum Week {
Sun(0,"星期天"), Mon(1,"星期一") , Tue(2,"星期二") , Wed(3,"星期三") , Thu(4,"星期四") , Fri(5,"星期五") , Sat(6,"星期六");
private final Integer value ;
private final String name;
private Week(Integer value,String name){
this.value=value;
this.name = name;
}
public int getValue() {
return value;
}
public String getName(){
return name;
}
}
public class EnumSimple {
public static void main(String[] args) {
Week.Fri.toString();
Week flag = Week.Fri;
switch (flag) {
case Fri:
System.out.println(flag.getName() + "----------" + flag.getValue() + "-----------" + flag.ordinal());
break;
case Sun:
System.out.println(flag.getName() + "----------" + flag.getValue() + "-----------" + flag.ordinal());
break;
default:
break;
}
}
}
3.实现带有抽象方法的枚举
public enum Week {
Sun(0,"星期天"){
public String getNextDay(){
return "星期一";
}
}, Mon(1,"星期一"){
public String getNextDay(){
return "星期二";
}
} , Tue(2,"星期二"){
public String getNextDay(){
return "星期三";
}
} , Wed(3,"星期三"){
public String getNextDay(){
return "星期四";
}
} , Thu(4,"星期四"){
public String getNextDay(){
return "星期五";
}
} , Fri(5,"星期五"){
public String getNextDay(){
return "星期六";
}
} , Sat(6,"星期六"){
public String getNextDay(){
return "星期日";
}
};
private final Integer value ;
private final String name;
private Week(Integer value,String name){
this.value=value;
this.name = name;
}
public int getValue() {
return value;
}
public String getName(){
return name;
}
public abstract String getNextDay();
}