一, 枚举定义
枚举不能定义在静态方法中
一般自定义的枚举类型都属于 Enum 的子类型 EnumType
它默认就有两个静态方法 (类方法):values() 和 valueOf()
values()返回的是 EnumType 类型的实例数组
valueOf()返回的是 EnumType 类型的实例
二,
举例: 自定义 Color 枚举类型
- Color{ WHITE, BLACK, GRAY }
- Color c = Color.GRAY;
那么:
Color.valueOf("BLACK") == Color.BLACK == Color.values()[1]
因为它们返回的都是 Color 类型
c.toString() == c.name()
因为它们返回的是字符串
三, 枚举的构造函数和成员变量
枚举的构造函数只能是 private
枚举的成员变量则不受限制, 但如果在枚举实例里面定义的方法需要访问枚举类型中的成员变量, 则该成员变量至少要是 protected, 否则无法继承
- package newpack17;
- interface d{
- public String getDescription();
- public int getI();
- }
- public enum AnyEnum implements d{
- Constants_A{
- public String getDescription() {
- return "我是枚举成员 A";
- }
- public int getI() {
- return i;
- }
- },
- Constants_B{
- public String getDescription() {
- return "我是枚举成员 B";
- }
- public int getI() {
- return i;
- }
- },
- Constants_E("枚举成员 E",88){
- public String getDescription() {
- return this.str;
- }
- public int getI() {
- return this.it;
- }
- },
- Constants_C,
- Constants_D{
- public String getDescription() {
- return "我是枚举成员 D";
- }
- public int getI() {
- return i;
- }
- };
- private AnyEnum(String str,int i) {
- this.str = str;
- this.it=i;
- }
- private AnyEnum() {}
- public String getDescription() {
- return "我是枚举成员 XXX";
- }
- public int getI() {
- return 10000;
- }
- public int it; // protected 也行, 但不能是 private
- protected String str;
- private static int i = 5; // 静态成员 public protected,private 都行
- public static void main(String[] args) {
- for(int i = 0; i<AnyEnum.values().length; i++) {
- System.out.println(AnyEnum.values()[i]+"调用 getDescription()方法为:"+AnyEnum.values()[i].getDescription());
- System.out.println(AnyEnum.values()[i]+"调用 getI()方法为:"+AnyEnum.values()[i].getI());
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2737116.html