枚举应该是一个有限集合组成的一个对象
一个简单的例子:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
枚举最简单的就是当常量用,但是比常量安全,最常用的就是在switch里面。
其实枚举可以当个普通的类使用,可以有变量,方法等。
当普通类使用的时候,其中有几个注意点:
- enum不可以有子类,因为enum是final的,
- enum不是继承其它类,因为它默认已经继承了Enum,但是可以实现Interface
- 构造方法是private或者是默认,不能是public的或者protected的
下面一个用作普通类的例子:
package tenum;
interface Next<T> {
T next();
}
public enum Week implements Next<Week> {
SUNDAY("Today is Sunday."), MONDAY("Today is Monday"), TUESDAY("Today is Tuesday"), WEDNESDAY(
"Today is wednesday"), THURSDAY(
"Today is Thursday"), FRIDAY("Today is Firday"), SATURDAY("Today is Saturday");
private String description;
Week(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
@Override
public Week next() {
switch (this) {
case SUNDAY:
return MONDAY;
case MONDAY:
return TUESDAY;
case TUESDAY:
return WEDNESDAY;
case WEDNESDAY:
return THURSDAY;
case THURSDAY:
return FRIDAY;
case FRIDAY:
return SATURDAY;
case SATURDAY:
return SUNDAY;
}
return null;
}
public static void main(String[] args) {
for (Week w : values()) {
System.out.println(w.getDescription());
}
System.out.println("------------------------------");
for (Week w : Week.class.getEnumConstants()) {
System.out.println(w.getDescription());
}
System.out.println("------------------------------");
//星期一之后2天是周几
System.out.println(Week.MONDAY.next().next().getDescription());
}
}
输出结果:
Today is Sunday.
Today is Monday
Today is Tuesday
Today is wednesday
Today is Thursday
Today is Firday
Today is Saturday
------------------------------
Today is Sunday.
Today is Monday
Today is Tuesday
Today is wednesday
Today is Thursday
Today is Firday
Today is Saturday
------------------------------
Today is wednesday
上面两种来获取所有元素,一种是调用values()
方法,一种是通过class 对象的getEnumConstants()
方法。
有趣的是values()
方法,enum 是继承Eunm.java
,但是Enum.java
里面并没有values()
方法。怎么来的呢?其实是编译器为我们自动生成的。如果你自己在定义这个方法,编译器就会报错“The enum Week already defines the method values() implicitly”。
让我们来看看编译器生成的class 文件。
Warning: Binary file Week contains tenum.Week
Compiled from "Week.java"
public final class tenum.Week extends java.lang.Enum<tenum.Week> implements tenum.Next<tenum.Week> {
public static final tenum.Week SUNDAY;
public static final tenum.Week MONDAY;
public static final tenum.Week TUESDAY;
public static final tenum.Week WEDNESDAY;
public static final tenum.Week THURSDAY;
public static final tenum.Week FRIDAY;
public static final tenum.Week SATURDAY;
static {};
public java.lang.String getDescription();
public tenum.Week next();
public static void main(java.lang.String[]);
public static tenum.Week[] values();
public static tenum.Week valueOf(java.lang.String);
public java.lang.Object next();
static int[] $SWITCH_TABLE$tenum$Week();
}
从上面可以看到几点,1)class 是final的,2)自动生成values()方法,3)继承了Enum类
参考:
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
https://www.ibm.com/developerworks/cn/java/j-lo-enum/index.html