在 JDK1.5 之前,我们定义常量都是: public static fianl....
。现在好了,有了枚举,可以把相关的常量分
组到一个枚举类型里,而且枚举提供了比常量更多的方法。
enum 枚举名 {
枚举体(常量列表)
}
所有的枚举类型隐性地继承自 java.lang.Enum
。枚举实质上还是类!而每个被枚举的成员实质就是一个枚举类型
的实例,他们默认都是public static final
修饰的。可以直接通过枚举类型名使用它们。
package com.example;
public enum SeasonEnum {
SPRING, SUMMER, AUTUMN, WINTER;
}
package com.example;
public class Test {
public static void main(String[] args) {
//每个枚举成员实际上是一个枚举实例
SeasonEnum spring = SeasonEnum.SPRING;
System.out.println(spring);
SeasonEnum summer = SeasonEnum.SUMMER;
System.out.println(summer);
SeasonEnum autumn = SeasonEnum.AUTUMN;
System.out.println(autumn);
SeasonEnum winter = SeasonEnum.WINTER;
System.out.println(winter);
System.out.println(SeasonEnum.SPRING);
System.out.println(SeasonEnum.SUMMER);
System.out.println(SeasonEnum.AUTUMN);
System.out.println(SeasonEnum.WINTER);
}
}
# 程序输出
SPRING
SUMMER
AUTUMN
WINTER
SPRING
SUMMER
AUTUMN
WINTER
我们可以给枚举中添加属性和方法:
package com.example;
public enum MessageEnum {
SYSTEM("1","系统消息"),
WEILAN_FOR_HUOZHU("2","围栏给货主发消息"),
WEILAN_FOR_CHEZHU("3","围栏给车主发消息"),
ORDER_STATE("4","运单状态消息"),
USER_FLEET("5","用户车队推送信息"),
VOICE_NOTICE("6","语音播报通知"),
ACCOUNT_DISABLE("7","账户禁用通知");
private String type; //类型
private String desc; //描述
private MessageEnum(String type,String desc){
this.type=type;
this.desc=desc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
package com.example;
public class Test2 {
public static void main(String[] args) {
//每个枚举成员实际上是一个枚举实例
MessageEnum message = MessageEnum.SYSTEM;
System.out.println(message);
System.out.println(message.getType());
System.out.println(message.getDesc());
}
}
# 程序输出
SYSTEM
1
系统消息