1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
/*
知识点:枚举
枚举是从java5开始提供的一种新的数据类型,是一个特殊的类,就是多个常量对象的集合
定义格式:
[修饰符] enum 枚举类名
{
常量A, 常量B, 常量C;
}
*/
//定义枚举
enum Weekday
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
//枚举类型中的Monday等价于原来的:public static final Weekday Monday = new Weekday();
}
class Employees
{
private Weekday restday; //一周的哪一天休息(数据类型为Weekday)
public Weekday getRestday()
{
return restday;
}
public void setRestday(Weekday restday) //数据类型为Weekday
{
this.restday = restday;
}
}
public class EnumerateExample
{
public static void main(String[] args)
{
Employees e = new Employees(); //创建员工对象
e.setRestday(Weekday.Wednesday); //通过类名.对象的方式来设置休息时间
Weekday restday = e.getRestday(); //用Weekday类型的变量restday来接收得到的值
if(restday == Weekday.Saturday || restday == Weekday.Sunday)
{
System.out.println("周末休息...");
}
else
{
System.out.println("周一至周五休息...");
}
}
}
/*
Weekday类的字节码文件内容(用java字节码反编译工具进行反编译后查看):
final class Weekday extends Enum //自定义的Weekday枚举类在底层里都是继承java.lang中的Enum
{
public static final Weekday Monday;
public static final Weekday Tuesday;
public static final Weekday Wednesday;
public static final Weekday Thursday;
public static final Weekday Friday;
public static final Weekday Saturday;
public static final Weekday Sunday;
private static final Weekday $VALUES[];
public static Weekday[] values()
{
return (Weekday[])$VALUES.clone();
}
public static Weekday valueOf(String s)
{
return (Weekday)Enum.valueOf(Weekday, s);
}
private Weekday(String s, int i)
{
super(s, i);
}
static
{
Monday = new Weekday("Monday", 0);
Tuesday = new Weekday("Tuesday", 1);
Wednesday = new Weekday("Wednesday", 2);
Thursday = new Weekday("Thursday", 3);
Friday = new Weekday("Friday", 4);
Saturday = new Weekday("Saturday", 5);
Sunday = new Weekday("Sunday", 6);
$VALUES = (new Weekday[] {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
});
}
}
*/
|
本文转自 TtrToby 51CTO博客,原文链接:http://blog.51cto.com/freshair/2055382