黑马程序员技术交流社区
标题:
枚举的代码问题?望大神解答
[打印本页]
作者:
腹黑生姜
时间:
2015-6-27 17:56
标题:
枚举的代码问题?望大神解答
这是枚举的代码
public class EnumDemo2
{
enum Weekday
{
SUN(5), MON(), TUE, WED, THU, FRI, SAT;
private Weekday()
{
System.out.println(this.name());
}
private Weekday(int day)
{
System.out.println(day);
}
}
public static void main(String[] args)
{
Weekday sun=Weekday.SUN;
System.out.println(sun.name());
}
}
------------------------------------------------------------
Weekday.SUN;具体是什么意思?望大神解答!
作者:
hhqnmlgb
时间:
2015-6-27 19:25
本帖最后由 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;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2