黑马程序员_简单类实现枚举_枚举的高级应用
程序员文章站
2022-06-16 16:58:42
...
----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流!----------------------
WeekD.java(普通的if....else判断)
public class WeekDay {
private WeekDay(){
}
public final static WeekDay SUN=new WeekDay();
public final static WeekDay SAT=new WeekDay();
public final static WeekDay FN=new WeekDay();
public final static WeekDay THU=new WeekDay();
public final static WeekDay WED=new WeekDay();
public final static WeekDay TUE=new WeekDay();
public final static WeekDay MON=new WeekDay();
public WeekDay nextDay(){
if(this==SUN){
return MON;
}else if(this==MON){
return TUE;
}else if(this==TUE){
return WED;
}else if(this==WED){
return THU;
}else if(this==THU){
return FN;
}else if(this==FN){
return SAT;
}else{
return SUN;
}
}
public String toString(){
if(this==SUN){
return "星期日";
}else if(this==SAT){
return "星期六";
}else if(this==FN){
return "星期五";
}else if(this==THU){
return "星期四";
}else if(this==WED){
return "星期三";
}else if(this==TUE){
return "星期二";
}else{
return "星期一";
}
}
}
AbstractWeekDay1.java(抽象nextDay()方法实现)
/*
采用抽象方法定义nextDay()就将大量的if...else语句转移成了一个个独立的类
如果想在一个类中编写完各个枚举类和测试调用类,那么可以将枚举定义成调用类的内部类。
*/
public abstract class AbstractWeekDay1 {
private AbstractWeekDay1(){
}
/*
为了避免写
if(this==SUN){
return MON;
}else{
return SUN;
}
就采用覆写抽象方法nextDay()
*/
public final static AbstractWeekDay1 SUN=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return SAT;
}
};
public final static AbstractWeekDay1 SAT=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return SUN;
}
};
public final static AbstractWeekDay1 FN=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return THU;
}
};
public final static AbstractWeekDay1 THU=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return WED;
}
};
public final static AbstractWeekDay1 WED=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return TUE;
}
};
public final static AbstractWeekDay1 TUE=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return MON;
}
};
public final static AbstractWeekDay1 MON=new AbstractWeekDay1(){
public AbstractWeekDay1 nextDay(){
return SUN;
}
};
public abstract AbstractWeekDay1 nextDay();
public String toString(){
if(this==SUN){
return "星期日";
}else if(this==SAT){
return "星期六";
}else if(this==FN){
return "星期五";
}else if(this==THU){
return "星期四";
}else if(this==WED){
return "星期三";
}else if(this==TUE){
return "星期二";
}else{
return "星期一";
}
}
}
测试用的EnumTest.java
public class EnumTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(AbstractWeekDay1.SUN.nextDay());
}
}
----------------------ASP.Net+Android+IOS开发.Net培训、期待与您交流!----------------------
上一篇: 开心果的营养价值如何?功效有哪些?
下一篇: 简单的使用枚举类