枚举是一种特殊的java类
1. 枚举的高级用法:enum中添加方法和自定义构造函数
public enum Day { Mon("Monday"),TUE("Tuesday"); private String description; private Day(String description){ this.description=description; }//自定义构造函数,定义为私有的防止外部调用, //是有编译器自己调用的,将前面括号里的Monday,Tuesday传入 public String getDesc(){//开放一个外部可以访问的方法,来获取枚举的构造函数传入的值 return this.description; } }
public enum MoneyEnum { USA("America","美国"),CHEN("China","中国"); private MoneyEnum(String code,String name){ this.code=code; this.name=name; } private String code; private String name; public String getCode() { return code; } public String getName() { return name; } //可以通过code来查询枚举 public static MoneyEnum getMoneyEnumByCode(String code){ if(code==null) return null; for (MoneyEnum moneyEnum : MoneyEnum.values()) { if(moneyEnum.getCode().equals(code)) return moneyEnum; } return null; } }
枚举的一般用法
public enum EnumColor { RED,GREEN,BLACK,WHITE,BROWN }
包含抽象方法的枚举类型
//包含抽象方法的枚举类型 //枚举类型经过编译器的处理,含抽象方法的将被处理成抽象类,否则处理成final类 public enum EnumColor { RED{ @Override public void printColor() { System.out.println("this is red"); } },GREEN{ @Override public void printColor() { System.out.println("this is green"); } }; public abstract void printColor(); public static void main(String[] args) { EnumColor.RED.printColor(); EnumColor.GREEN.printColor(); } }
参考:
https://blog.csdn.net/javazejian/article/details/71333103#comments