本帖最后由 hhqnmlgb 于 2015-6-27 19:54 编辑
其实枚举也是用普通类实现的
它会自动私有化构造函数
字段都是:public static 枚举的类型 = new 类型();- enum Weekday
- {
- SUN, MON, TUE, WED, THU, FRI, SAT;
- }
- //上面的枚举可以看成这样一个类:
- class Week
- {
- private Week(){}
- public static Week SUN=new Week();
- public static Week MON=new Week();
- public static Week TUE=new Week();
- public static Week WED=new Week();
- public static Week THU=new Week();
- public static Week FRI=new Week();
- public static Week SAT=new Week();
- }
复制代码
Weekday.SUN;就是Weekday型的一个静态字段
稍复杂的枚举:
- enum Weekday
- {
- SUN(0), MON(1), TUE, WED, THU, FRI, SAT;//通过"()"来传参数指定用哪个构造方法
- private int day;
- private Weekday(){}
- private Weekday(int day)
- {
- this.day=day;
- }
- public int getDay()
- {
- return day;
- }
- }
- //上面的枚举可以看成这样一个类:
- class Week
- {
- private int day;
- private Week(){}
- private Week(int day)
- {
- this.day=day;
- }
- public static Week SUN=new Week(0);
- public static Week MON=new Week(1);
- public static Week TUE=new Week();
- public static Week WED=new Week();
- public static Week THU=new Week();
- public static Week FRI=new Week();
- public static Week SAT=new Week();
-
- public int getDay()
- {
- return day;
- }
- }
复制代码
|