枚举的作用介绍
1、枚举就是让某个类型的变量的取值只能为若干个固定值中的一个,否则,编译器报错。枚举可以让编译器在编译时就可以控制源程序中填写的非法值,普通变量的方式在开发阶段无法实现这一目标。
2、枚举就是一种特殊的类,其中的每个元素都是该类中的一个实例对象
用普通类模拟枚举的实现原理
WeekDay.java1、私有的构造方法
2、每个元素分别用一个公有的静态成员变量表示
3、可以有若干个共有的方法或抽象方法。采用抽象方法定义nextDay就可将大量的if.else语句转移成一个个独立的类
public class WeekDay { private WeekDay(){} public final static WeekDay SUN = new WeekDay(); public final static WeekDay MON = new WeekDay(); public WeekDay nextDay(){ if( this == SUN ){ return MON; }else { return SUN; } } public String toString(){ return this==SUN?"SUN":"MON"; } }
采用抽象方法:
public abstract class WeekDay {
private WeekDay(){}
public final static WeekDay SUN = new WeekDay(){
@Override
public WeekDay nextDay() {
// TODO Auto-generated method stub
return MON;
}
};
public final static WeekDay MON = new WeekDay(){
@Override
public WeekDay nextDay() {
// TODO Auto-generated method stub
return SUN;
}
};
public abstract WeekDay nextDay();
public String toString(){
return this==SUN?"SUN":"MON";
}
}
EnumTest.java
public class EnumTest {
public static void main(String[] args){
WeekDay weekDay = WeekDay.MON;
System.out.println(weekDay.nextDay());
}
}
枚举的基本应用
public class EnumTest {
public static void main(String[] args) {
WeekDay mon = WeekDay.MON;
System.out.println(mon);//名称为MON
System.out.println(mon.name());//名称为MON
System.out.println(WeekDay.valueOf("SUN"));//字符串变为WeekDay对象,打印出SUN
System.out.println(WeekDay.values().length);//7
}
public enum WeekDay{
SUN,MON,TUE,WED,THI,FRI,SAT
}
}
实现带有构造方法的枚举
public class EnumTest {
public static void main(String[] args){
WeekDay weekDay = WeekDay.MON;
}
public enum WeekDay{
SUN,MON,TUE,WED,THI,FRI,SAT;
private WeekDay() {
System.out.println("first constructor");
}
private WeekDay(int day){
System.out.println("second constructor");
}
}
}
结果:
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
first constructor
因为枚举类的每个静态对象,在使用类的时候就会创建
若采用方式:SUN,MON(1),TUE,WED,THI,FRI,SAT,表示在创建MON元素的时候使用第二个构造器,结果:
first constructor
second constructor
first constructor
first constructor
first constructor
first constructor
first constructor
实现带有抽象方法的枚举
public class EnumTest {
public static void main(String[] args){
TrafficLamp trafficLamp = TrafficLamp.RED;
System.out.println(trafficLamp.nextLamp());
}
public enum TrafficLamp{
RED(30){
public TrafficLamp nextLamp() {
return GREEN;
}
},GREEN(45){
public TrafficLamp nextLamp() {
return YELLOW;
}
},YELLOW(5){
public TrafficLamp nextLamp() {
return RED;
}
};
//抽象方法
public abstract TrafficLamp nextLamp();
private int time;
private TrafficLamp(int time){
this.time = time;
}
}
}
结果:
GREEN