标签:
先模拟一下枚举类:
package enumtest; public class EnumTest { public static void main(String[] args) { WeekDay day = WeekDay.SUN; System.out.println(day.nextDay()); } } //先模拟一个 枚举 (说明白,枚举形成的基本思路) abstract class WeekDay { private WeekDay(){} //上来就把它的构造器私有化,因为枚举的实例是固定的 public static final WeekDay MON = new WeekDay(){ //定义(成员)内部类 @Override public WeekDay nextDay() { return WeekDay.SUN; } }; public static final WeekDay SUN = new WeekDay(){ @Override public WeekDay nextDay() { return WeekDay.MON; } }; public abstract WeekDay nextDay(); @Override public String toString() { return this==SUN?"SUN":"MON"; } }
Java中的枚举:(jdk1.5以上)
package enumtest; public class EnumTest { public static void main(String[] args) { WeekDay day = WeekDay.SUN; System.out.println(day); System.out.println(day.name()); System.out.println(day.ordinal()); //枚举实例在枚举类中的位置 System.out.println(day.toString()); System.out.println(WeekDay.valueOf("MON")); } } enum WeekDay { SUN,MON(),THU(1),WES,THR,FRI,SAT; //构造方法只能私有化 private WeekDay() { System.out.println("调用了无参构造器..."); } private WeekDay(int i) { System.out.println("调用了有参构造器"); } }
结果如下:
标签:
原文地址:http://www.cnblogs.com/bluechip/p/4176183.html