试了下enum,感觉没怎么好用;
比如我要表示状态;
public enum Status {
SUCCEED(1), FAIL(2);
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
private int index;
private Status(int index) {
this.index = index;
}
}
要获取数值还要Status.FAIL.getIndex()
如果是常量,直接就Status.FAIL就ok了
大家怎么看?
------解决思路----------------------
多个属性时习惯用enum,单个属性还是static final方便。
public enum Status {
SUCCEED(1,“成功”), FAIL(2,"失败");
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
private int index;
private String text;
private Status(int index, String text) {
this.index = index;
this.text=text;
}
}
------解决思路----------------------
常量是一旦定义就不可修改的值,在开发中,如果有多个常量,需要定义多个常量;如:
public static final String MONDAY="周一";
public static final String TUESDAY ="周二";
public static final String WEDNESDAY="周三";
public static final String THURSDAY="周四";
public static final String FRIDAY="周五;
public static final String SATURDAY ="周六";
public static final String SUNDAY ="周日";
这样定义,显然比较费劲,枚举你可以理解为是对常量的封装,它是一个特殊的类。可以有自己自定义的方法,自定义的属性和构造函数。其次,变量的类型可以是枚举类型,这样就限定了变量的取值范围。如:
定义一个枚举
public enum WEEK{
MONDAY("周一"),TUESDAY(),WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY;
//定义私有构造函数,给这些常量赋值
private String str;
public String getStr(){
return this.str;
}
}
定义一个变量为枚举类型
WEEK w = WEEK.MONDAY;
System.out.println(s.getStr());