枚举的变形
实例:星期
技术要求:1、表示一个星期的每一天
2、获取下一个是星期几
技术要点:1、使用普通类模拟枚举的实现
2、private构造方法
3、使用final static表示每一天(常量)
4、提供几个公共接口获取下一个是星期几
public class Weekday{
public final static Weekday SUN= new Weekday();
public final static Weekday MON= new Weekday();
public final static Weekday TUS= new Weekday();
public final static Weekday WED= new Weekday();
public final static Weekday THS= new Weekday();
public final static Weekday FRI= new Weekday();
public final static Weekday SAT= new Weekday();
private Weekday(){}
public Weekday getNextDay(){
if(this == ) return ;
else if(this == SUN) return MON;
else if(this == MON) return TUS;
else if(this == TUS) return WED;
else if(this == WED) return THS;
else if(this == THS) return SAT;
else return SUN;
}
}
//main()
Weekday day = Weekday.SUN;
day = day.getNextDay();
技术要点:1、使用匿名内部类来去掉大量的if分支语句
2、声明一个abstrac方法,匿名内部类会实现该方法
public class Weekday{
public final static Weekday SUN= new Weekday(){
@Override
public Weekday(){ return MON;}};
public final static Weekday MON= new Weekday(){
@Override
public Weekday(){ return TUS;}};;
public final static Weekday TUS= new Weekday(){
@Override
public Weekday(){ return WED;}};;
public final static Weekday WED= new Weekday(){
@Override
public Weekday(){ return THS;}};;
public final static Weekday THS= new Weekday(){
@Override
public Weekday(){ return FRI;}};;
public final static Weekday FRI= new Weekday(){
@Override
public Weekday(){ return SAT;}};;
public final static Weekday SAT= new Weekday(){
@Override
public Weekday(){ return SUN;}};;
private Weekday(){}
public abstract Weekday getNextDay();
}
//main()
Weekday day = Weekday.SUN;
day = day.getNextDay();
技术要点:1、jdk1.5提供了枚举类型
2、可使用enum来解决一组静态常量的集合
3、enum也是一种类,都继承Enum
4、可带有方法、构造器、抽象方法
5、提供一些操作方法
enum Weekday{
SUN("Frist day"){//匿名内部类体,实现构造方法}, MON, TUS, WED, THS, FRI, SAT; //相当类的静态常量,并且位于第一行
private String describe; //枚举成员
private Weekday(){} //构造方法必须为private,默认提供
private Weekday(String describe){this.describe = describe;}
public abstract Weekday getNextDay(); //抽象方法
}
技术要点:1、Enum提供静态方法valueOf(String),该法根据字符串描述获得枚举实例
2、上例可以不使用抽象方法,也具有类似的功能
//main()
Weekday sun = Enum.valueOf("Frist day"); //SUN
|
|