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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
package cn.xpshuai.java1;
/**
* @author: 剑胆琴心
* @create: 2021-01-24 18:18
* @功能:枚举类
*
* 类的对象只有有限个、确定的。我们称此类为枚举类
* 当需要定义一组常量时,强烈建议使用枚举类
* 如果枚举类中只有一个对象,则可以作为单例模式的实现方式。
*
*
* 如何定义枚举类
* 方法1:jdk5.0之前:之定义枚举类
* 方法2:jdk5.0,可以使用enum关键字定义枚举类(常用)
*
*
* Enum中常用方法:
* value() 返回枚举类型的对象数据
* valueOf() 可以把一个字符串转为对应的枚举类对象(要求字符串必须是枚举类对象的"名字")
* toString() 返回当前枚举类对象常量的名称
*/
public class EnumTest {
public static void main(String[] args) {
Season spring = Season.SPRING;
System.out.println(spring);
// //jdk5.0,可以使用enum关键字定义枚举类(常用)
//定义的枚举类继承于java.lang.Enum
Season1 spring1 = Season1.SPRING;
// toString()
System.out.println(spring1);
System.out.println(Season1.class.getSuperclass());
//values()
Season1[] values = Season1.values();
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
// valueOf(String objName): 根据提供objName, 返回枚举类中对象名是objName的对象
// 如果没有,则抛出异常
Season1 winter = Season1.valueOf("WINTER");
System.out.println(winter);
}
}
//jdk5.0之前:自定义枚举类
class Season{
//1.声明Season对象的属性
private final String seasonName;
private final String seasonDesc;
//2.私有化类的构造器, 并给对象属性赋值
private Season(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3.提供当前枚举类的对象的多个对象 public static final
public static final Season SPRING = new Season("春天", "春暖花开");
public static final Season SUMMER = new Season("夏天", "夏日炎炎");
public static final Season AUTOM = new Season("秋天", "秋高气爽");
public static final Season WINTER = new Season("冬天", "冰天雪地");
//4.其他诉求:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
//4.其他诉求:提供toString()
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
// //jdk5.0,可以使用enum关键字定义枚举类(常用)
enum Season1{
// 1.提供当前枚举类的帝乡,多个对象之间用,隔开
SPRING("春天", "春暖花开"),
SUMMER("夏天", "夏日炎炎"),
AUTOM("秋天", "秋高气爽"),
WINTER("冬天", "冰天雪地");
//2.声明Season对象的属性
private final String seasonName;
private final String seasonDesc;
//2.私有化类的构造器, 并给对象属性赋值
private Season1(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
//3.提供当前枚举类的对象的多个对象 public static final
//4.其他诉求:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
|