java枚举

之前对枚举不是很了解,今天用到了,就明白了,直接放出一个枚举类型,说明一下用法:

 1 public enum FuluBillStatus {
 2 
 3     BILL_STATUS_unprocessed(1, "未处理"),
 4     BILL_STATUS_processed(2, "处理中"),
 5     BILL_STATUS_successful(3, "成功"),//(支付成功)
 6     BILL_STATUS_failed(4, "失败");//(支付失败)
 7 
 8     private final int index;
 9     private final String text;
10 
11     public int getIndex() {
12         return index;
13     }
14 
15     public String getText() {
16         return text;
17     }
18 
19     FuluBillStatus(int index, String text) {
20         this.index = index;
21         this.text = text;
22     }
23 
24     public static String getTextByIndex(int index) {
25         for (FuluBillStatus status : values()) {
26             if (status.index == index) {
27                 return status.text;
28             }
29         }
30         return "";
31     }
32 }
FuluBillStatus就相当于一个java类;
其中index和text就是这个类的2个属性;
FuluBillStatus(int index, String text) {}就是一个构造器;
BILL_STATUS_unprocessed(1, "未处理")就是创建了一个对象,示例中创建了4个对象,

因为属性都是用final修饰的,所以不能修改,一开始就创建了4个固定的对象,之后就不能再创建对象了;

getTextByIndex(int index)静态方法就是根据index得到对应的text【从4个对象中找对应的text】

备注说明:定义对象要放入属性定义之前,而且是用逗号, 分隔开多个对象,最后一个对象用分号;

使用枚举的场景:需要键值对的情况,考虑使用枚举

 


posted @ 2019-05-15 15:41  戴眼镜的蚂蚁  阅读(194)  评论(0编辑  收藏  举报