廖雪峰Java2面向对象编程-6Java核心类-5枚举类
1.直接定义常量
class Weekday {
//定义int常量
public static final int SUN = 0;
public static final int MON = 1;
public static final int TUE = 2;
public static final int WED = 3;
public static final int THU = 4;
public static final int FRI = 5;
public static final int SAT = 6;
//定义String常量
public static final String RED = "r";
public static final String GREEN = "g";
public static final String BLUE = "b";
}
public class Main {
public static void main(String[] args){
int day = 5;
String color = "a";
if(day == Weekday.FRI){
System.out.println(day);
}
if(color.equals(Weekday.BLUE)){
System.out.println(color);
}
}
}
直接定义常量的缺点:编译器无法检查常量的内容。常量发生改变,如r变成R,很多逻辑会报错。因此Java提供了枚举类型。
2.通过enum定义常量
- 通过enum关键字可以定义常量类型
- 常量本身带有类型信息
- 使用 == 比较 if(day == Weekday.FRI)
enum定义的类型实际上是class:
- enum继承自java.lang.Enum
- 不能通过new创建实例
- 所有常量都是唯一类型(引用类型):每个常量在JVM中是唯一的,因此可以使用==
- 可以用于switch语句
public enum Weekday{
SUN,MON,TUE,WED,THU,FRI,SAT
}
public class Main {
public static void main(String[] args){
for(Weekday day:Weekday.values()){
//Weekday.value()获取所有常量的数组
System.out.println(day.name());//打印常量的name
}
Weekday fri = Weekday.FRI;//获取某个常量的引用类型
System.out.println("FRI.name() = " + fri.name());//获取name
System.out.println("FRI.ordinal() = " + fri.ordinal());//获取编号
System.out.println(Weekday.valueOf("FRI").name());//Weekday.valueOf(String)获取某个指定的常量
System.out.println(Weekday.valueOf("ABC"));
}
package com.csj2018.lxf;
public enum Weekday {
SUN("星期日"),
MON("星期一"),
TUE("星期二"),
WEN("星期三"),
THR("星期四"),
FRI("星期五"),
SAT("星期六");
private String chinese;
private Weekday(String chinese) {
this.chinese = chinese;
}
public String getChinese() {
return chinese;
}
}
package com.csj2018.lxf;
import org.junit.Test;
public class ForWeekday {
@Test
public void test() {
Weekday sun = Weekday.SUN;
System.out.println(sun.getChinese());
}
}
3. 总结:
- enum可以定义常量类型,它被编译器编译为:final class Xxx extends Enum
- name()获取常量定义的字符串,注意不要使用toString(),toString()是可以被覆写的
- ordinal()返回常量定义的顺序(无实质意义)
- 可以为enum类编写构造方法、字段和方法。enum的构造方法必须是private
- 构造方法申明为private