tusConstant.fruit, StatusConstant.banana);
Goods goods_2 = new Goods(StatusConstant.eleProduct, StatusConstant.phone);
System.out.println(goods.getName());
System.out.println(goods_2.getName());
}
}
我们可以发现类常量
的方式,的确很方便,也没有接口常量多继承
的烦恼。但是她所能承接的信息,维度不够,只能一个字段的去承接信息,然而当项目复杂的话,我们希望往往其能承接更多维度的信息,类似于对象一样,拥有更多的属性
{
"name": ...,
"type": ...,
...
}
这时候,我们本文的主角,枚举就闪亮登场了!
枚举
什么是枚举?
枚举是一种特殊的类,所有的枚举类都是Enum类的子类,就类似Object类一样,由于java类是单继承的,所以不能在继承其他类或者枚举了。
枚举变量不能使用其他的数据,只能使用枚举中常量赋值。能提高程序的安全性。
格式:
public enum 枚举名{
//枚举的取值范围
}
枚举常量
我们先定义一个枚举类,来定义常量:
public enum ContentEnums {
Apple(1,"苹果"),
Banana(2,"香蕉"),
Grape(3,"葡萄"),
Computer(101,"电脑"),
Phone(102,"手机"),
Camera(103,"摄像机"),
Fruit(10010,"fruit"),
EleProduct(10020,"eleProduct");
private Integer code;
private String desc;
ContentEnums(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
测试类:
public class GoodsTest4 {
public static void main(String[] args) throws InterruptedException {
Goods goods = new Goods(ContentEnums.Fruit.getDesc(), ContentEnums.Apple.getCode());
Goods goods_2 = new Goods(ContentEnums.EleProduct.getDesc(), ContentEnums.Phone.getCode());
System.out.println(goods.getName());
System.out.println(goods_2.getName());
}
}
看到这大家可能就有疑问了,枚举
和常量类
相比,有什么优点吗?
- 枚举其实是一种特殊的类,可以承接对象的多维信息,但是常量类往往只能承接字段,信息比较单一
- 枚举可以搭配switch语句使用,来代替
if/else
ContentEnums content = ContentEnums.Apple;
switch (content) {
case Apple:
System.out.println("苹果");
break;
case Banana:
System.out.println("香蕉");
break;
case Grape:
System.out.println("葡萄");
break;
default:
System.out.println("未找到匹配类型");
}
- enum 有一个非常有趣的特性,它可以为enum实例编写方法
public enum MethodEnums {
VERSION {
@Override
String getInfo() {
return System.getProperty("java.version");
}
},
DATE_TIME {
@Override
String getInfo() {
return
DateFormat.getDateInstance()
.format(new Date());
}
};
abstract String getInfo();
public static void main(String[] args) {
for(MethodEnums csm : values()) {
System.out.println(csm.getInfo());
}
}
}
结果:
1.8.0_271
2022-9-21
除了抽象方法,普通方法也是可以的,这里就不展示了
- 网上还有其他一些优点,感觉没啥特别值得说的
限制输入的类型
我们可以通过枚举来将相关的状态,类型放在一起,文章一开头,但我们怎么才能限制类的输入值呢?其实很简单,别被绕进去,我们只需将输入类型 改为指定的枚举即可
我们改造一下Goods类:
public class Goods {
/**
* 商品名称
*/
private String name;
/**
* 商品类型
*/
private Integer type;
// public Goods(String name, Integer type) {
// this.name = name;
// this.type = type;
// }
public Goods() {//防止外部实例化
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public static Goods addGoods(ContentEnums enums){
Goods goods = new Goods();
goods.setName(enums.getDesc());
goods.setType(enums.getCode());
return goods;
}
}
测试类:
public class GoodsTest5 {
public static void main(String[] args) throws InterruptedException {
Goods goods = Goo