1 import org.junit.Test;View Code
2
3 public class Demo {
4
5 /**
6 * 枚举
7 */
8 @Test
9 public void test() {
10
11 print(Grade.B);
12
13 }
14 //测试枚举的常用方法
15 @Test
16 public void test2(){
17
18 System.out.println(Grade.C.name());
19 System.out.println(Grade.C.ordinal());
20
21 String str = "B";
22 Grade g = Grade.valueOf(Grade.class, str);
23 System.out.println(g);
24
25 Grade gs[] = Grade.values();
26 for(Grade g2 : gs){
27
28 System.out.println(g2);
29 }
30 }
31
32 public void print(Grade g) {
33 String value = g.localeValue();
34 System.out.println(value);
35
36 }
37
38 }
39
40 //如何定义枚举的构造函数、方法和字段、去封装更多的信息
41 enum Grade {// class A 100-90 优 B 89-80 良 C 79-70 一般 D 69-60 差 E 59-0 不及格
42
43 A("100-90"){
44
45 public String localeValue(){
46 return "优";
47 }
48 },
49 B("89-80"){
50 public String localeValue(){
51 return "良";
52 }
53 },
54 C("79-70"){
55 public String localeValue(){
56 return "一般 ";
57 }
58 },
59 D("69-60"){
60 public String localeValue(){
61 return "差";
62 }
63 },
64 E("59-0"){
65 public String localeValue(){
66 return "不及格";
67 }
68 };// Object
69
70 private String value; // 封装每个对象对应的分数
71
72 private Grade(String value) {
73 this.value = value;
74 }
75
76 public String getValue() {
77
78 return this.value;
79 }
80
81 public abstract String localeValue();
82 }
83
84 /*
85 * class Grade{
86 *
87 * private Grade(){}
88 *
89 * public static final Grade A = new Grade(); public static final Grade B = new
90 * Grade(); public static final Grade C = new Grade(); public static final Grade
91 * D = new Grade(); public static final Grade E = new Grade(); }
92 */