本帖最后由 wangpan 于 2013-6-3 21:51 编辑
这是用普通类实现的枚举:
- <P>
- package fighting;</P>
- <P>public class WeekDay {
- private WeekDay(){
-
- }
- public final static WeekDay SUN = new WeekDay();
- public final static WeekDay MON = new WeekDay();
- public final static WeekDay TUE = new WeekDay();
- public final static WeekDay WED = new WeekDay();
- public final static WeekDay THU = new WeekDay();
- public final static WeekDay FRI = new WeekDay();
- public final static WeekDay SAT = new WeekDay();</P>
- <P>
- public WeekDay nextDay(){
- System.out.println("传过来的对象是:"+this);
- if(this == SUN){
- System.out.println("111111111");
- return MON;
- }else if(this == MON){
- System.out.println("2222222222");
- return TUE;
- }else if(this == TUE){
- System.out.println("33333333");
- return WED;
- }else if(this == WED){
- System.out.println("44444444");
- return THU;
- }else if(this == THU){
- System.out.println("555555555");
- return FRI;
- }else if(this == FRI){
- System.out.println("66666666");
- return SAT;
- }else{
- System.out.println("77777777");
- return SUN;
- }
- }
- public String toString(){
- if(this == SUN){
- return "Sunday";
- }else if(this == MON){
- return "Monday";
- }else if(this == TUE){
- return "Tuesday";
- }else if(this == WED){
- return "Wednesday";
- }else if(this == THU){
- return "Thursday";
- }else if(this == FRI){
- return "Friday";
- }else{
- return "Saturday";
- }</P>
- <P> }
- }
- </P>
复制代码 这是调用枚举类的类:
- <P>package fighting;
- public class EnumDemo {</P>
- <P> public static void main(String[] args) {
- WeekDay weekDay0 = WeekDay.SUN;
- System.out.println("下一天是:"+weekDay0.nextDay());
- System.out.println("---------------");
-
- WeekDay weekDay1 = WeekDay.MON;
- System.out.println("下一天是:"+weekDay1.nextDay());
- System.out.println("---------------");</P>
- <P> WeekDay weekDay2 = WeekDay.TUE;
- System.out.println("下一天是:"+weekDay2.nextDay());
- System.out.println("---------------");</P>
- <P> WeekDay weekDay3 = WeekDay.WED;
- System.out.println("下一天是:"+weekDay3.nextDay());
- System.out.println("---------------");</P>
- <P> WeekDay weekDay4 = WeekDay.THU;
- System.out.println("下一天是:"+weekDay4.nextDay());
- System.out.println("---------------");</P>
- <P> WeekDay weekDay5 = WeekDay.FRI;
- System.out.println("下一天是:"+weekDay5.nextDay());
- System.out.println("---------------");</P>
- <P> WeekDay weekDay6 = WeekDay.SAT;
- System.out.println("下一天是:"+weekDay6.nextDay());
- }</P>
- <P>}
- </P>
复制代码 运行结果是这样:
传过来的对象是:Sunday
111111111
下一天是:Monday
---------------
传过来的对象是:Monday
2222222222
下一天是:Tuesday
---------------
传过来的对象是:Tuesday
33333333
下一天是:Wednesday
---------------
传过来的对象是:Wednesday
44444444
下一天是:Thursday
---------------
传过来的对象是:Thursday
555555555
下一天是:Friday
---------------
传过来的对象是:Friday
66666666
下一天是:Saturday
---------------
传过来的对象是:Saturday
77777777
下一天是:Sunday
结果是正确的,想问一下,枚举类中的toString()方法有什么作用?
|