java的枚举2
首先先理解一下java中枚举的本质。
java的世界中一切皆是类,下面通过一个例子解释一下enum的本质:
package cn.xnchall.enumeration; public class Grade { public void test() { print(grade.A); } public void print(grade g) { //print A B C D E } } /*class grade{ private grade(){} public static final grade A = new grade(); public static final grade B = new grade(); public static final grade C = new grade(); public static final grade D = new grade(); public static final grade E = new grade(); }*/ enum grade{ //class A,B,C,D,E; //object }
grade类和grade枚举类型作用是一样的,就是说枚举类型是一个比较严格的类。它不允许在外部new grade类,因为底层实现是private的。外部要想实现new操作,必须在grade的内部实现。
下面正式介绍enumeration!
1.定义枚举的构造函数、方法和字段
package cn.xnchall.enumeration; public class Dome { public static void test() { print(grade.A); } public static void print(grade g) { //print A B C D E System.out.println(g.getValue()); } public static void main(String[] args){ test(); } } /*class grade{ private grade(){} public static final grade A = new grade(); public static final grade B = new grade(); public static final grade C = new grade(); public static final grade D = new grade(); public static final grade E = new grade(); }*/ enum grade{ //class A 100-90 B 89-80 C 79-70 D 69-60 E 59-0 A("100-90") ,B("89-80") ,C("79-70") ,D("69-60") ,E("59-0") ; private String value; //每个字段的分数 private grade(String value) { this.value = value; } public String getValue() { return this.value; } }
上面将会执行得到的结果是:100-90
未完待续
将会补充:带有抽象方法的枚举
2.带有抽象方法的枚举
package cn.xnchall.enumeration; public class Dome { public static void test() { print(grade.A); } public static void print(grade g) { //print A B C D E System.out.println(g.vValue()); } public static void main(String[] args){ test(); } } /*class grade{ private grade(){} public static final grade A = new grade(); public static final grade B = new grade(); public static final grade C = new grade(); public static final grade D = new grade(); public static final grade E = new grade(); }*/ enum grade{ //class A 100-90优秀 B 89-80良好 C 79-70一般 D 69-60及格 E 59-0不及格 A("100-90"){ public String vValue() { return "优秀"; } } ,B("89-80"){ public String vValue() { return "良好"; } } ,C("79-70"){ public String vValue() { return "一般"; } } ,D("69-60"){ public String vValue() { return "及格"; } } ,E("59-0"){ public String vValue() { return "不及格"; } } ; private String value; //每个字段的分数 private grade(String value) { this.value = value; } public String getValue() { return this.value; } public abstract String vValue(); }
上面代码执行的结果是:优秀
仔细研究上面的代码,很容易理解。
总之,java的世界“一切皆是类”,枚举就是枚举类,它里边的数据就是枚举的对象。当然了它也具有类的其他属性。