首页 > 代码库 > 尝试理解枚举
尝试理解枚举
先模拟一下枚举类:
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("调用了有参构造器"); } }
结果如下:
尝试理解枚举
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。