枚举类是Java语言列举类中普通基础的一个类。定义和class类的区别是用关键字enum修饰。定义格式如下:
{ClassModifier} enum
TypeIdentifier [ClassImplements] EnumBody
ClassModifier 默认为public,
TypeIdentifier 实际为枚举类的类名
EnumBody 即为枚举类的内容。
body里边可以自定义方法。
关于文档中的构造器定义有如下需注意的地方:
1.构造器方法只能私有。如果没有显示声明默认也为私有。It is a compile-time error if a constructor declaration in an enum declaration is public
or protected
2.构造器方法中不能有调用父类方法的语句。It is a compile-time error if a constructor declaration in an enum declaration contains a superclass constructor invocation statement
3.文档中声明的 (String name,int ordinal)的构造方法是隐式声明 和编译器有很大关系。
代码如下:
1 enum Color { 2 RED, GREEN, BLACK; 3 4 /** 5 * 自有实例方法 6 */ 7 8 protected void saySomething(Color col) { 9 System.out.println("调用到我了: " + col.toString() ); 10 } 11 12 /** 13 * 自有静态方法 14 */ 15 public static void directCall() { 16 System.out.println("调用到静态方法了"); 17 } 18 19 }
测试方法:
class Test { public static void main(String[] args) { System.out.println(Arrays.toString(Color.values())); // [RED, GREEN, BLUE] System.out.println(Color.values()[0].getClass()); // class com.ioc.test.enums.Color System.out.println(Color.valueOf("RED")); // RED 返回枚举值的字符串形式 for (Color col: Color.values()) { System.out.println(col.ordinal()); // 返回每个枚举值在枚举中声明的下标 col.saySomething(col); // 调用枚举类自己的实例方法 } Color.directCall(); }
输出结果:
valueOf(): 返回枚举类里每个属性的字符串值
values(): 返回枚举类的实例。该方法由构造器提供,文档中并未列出。
ordinal() : 该方法由final修饰,只能由类的实例调用,返回每个枚举值的下标。
原文:https://www.cnblogs.com/wuyaguoke/p/14673908.html