为什么要用枚举?
枚举就是要让某个类型的变量的取值只能为若干个固定值中的一个,否则编译器就会
报错。
用普通类的方法模拟枚举的实现原理
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 class EnumTest{ public static void main(String []args)throws Exception{ WeekDay weekday=WeekDay.MON; System.out.println(weekday.nextDay()); } } 结果打印输出:SUN
采用抽象方法---把大量的if-else语句转移成一个个独立的类
public abstract class WeekDay { private WeekDay(){} public final static WeekDay SUN=new WeekDay(){ @Override public WeekDay nextDay() { // TODO Auto-generated method stub return MON; }};//内部类没有名称是WeekDay的子类并且创建了一个对象 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"; } } public class EnumTest{ public static void main(String []args)throws Exception{ WeekDay weekday=WeekDay.MON; System.out.println(weekday.nextDay()); } } 同样可以得到
以下是一个基本的枚举类
public class EnumTest{ public static void main(String []args)throws Exception{ //枚举定义变量的时候只能给定义的元素 WeekDay week2=WeekDay.SUN; System.out.println(week2); System.out.println(week2.name());//打印自己的名字 System.out.println(week2.ordinal());//排行 System.out.println(Week2.valueOf("SUN"));//怎样把一个串变成一个对象(valueOf()) System.out.println(Week2.values().length)//把枚举中的每个元素都存储在数组里 } public enum WeekDay{ SUN,MON,TUE,WEN,THI,FRI,SAT; } }
实现带有构造方法的枚举
public class EnumTest{ public static void main(String []args)throws Exception{ //枚举定义变量的时候只能给定义的元素 WeekDay week2=WeekDay.SUN; System.out.println(week2); System.out.println(week2.name());//打印自己的名字 System.out.println(week2.ordinal());//排行 System.out.println(Week2.valueOf("SUN").toString());//怎样把一个串变成一个对象(valueOf()) System.out.println(Week2.values().length)//把枚举中的每个元素都存储在数组里 } public enum WeekDay{ SUN(1),MON,TUE,WEN,THI,FRI,SAT; //实现构造方法的枚举----要求要是私有的并且在元素后面 private WeekDay(){System.out.println("first");}//默认调用 private WeekDay(int day){System.out.println("second");}//需要在元素写成SUN(1) } }
实现带有抽象方法的枚举
public class EnumTest{ public static void main(String []args)throws Exception{ new Date(300){};//子类的构造方法要调用父类构造方法 } public enum TrafficLamp{ RED(30){ public TrafficLamp nextLamp(){ return GREEN; } },GREEN(45){ public TrafficLamp nextLamp(){ return YELLOW; } },YEELOW(5){ public TrafficLamp nextLamp(){ return RED; } }; public abstract TrafficLamp nextLamp(); private int time; private TrafficLamp(int time){this.time=time;} } }