其实枚举就是一类实例化对象的集合
下面是一个枚举的标准设计:
package work;
/**
*
* 用户类型
* 1 付费用户
* 0 未付费用户
*
*
* @author sun_guodong
* @date 2018年8月30日
*/
public enum UserType {
pay(1),nopay(0);
private Integer value;
UserType(Integer value){
this.value=value;
}
public Integer getValue() {
return value;
}
}
枚举作为类的扩展主要有以下几个功能:
1.代码可读性强
比如通常我们在数据库存用户类型的时候用数字代替字符串,我们如果直接传数字的话,不能直观的知道传入的用户类型是什么。但是我们可以传入 UserType.pay
2.安全性
如果直接传数字,那么代码中可随意传入数字,但是用枚举就只能传入上面范围的值。
public class User {
private Integer userType;
public Integer getUserType() {
return userType;
}
public void setUserType(UserType userType) {
this.userType = userType.getValue();
}
}
也可以直接通过UserType.pay.getValue()获得值1