一下是老师在枚举中讲的用普通类实现枚举功能的代码,这里面写到一个toString方法,是将返回值以字符串形式打印出,但这里并没有调用toString方法,请问为什么这样写呢?可不可以将最后的打印语句写成:System.out.println(weekDay.nextDay().toString());
public abstract class WeekDay
{
private WeekDay(){} //构造方法私有化,避免建立对象
public final static WeekDay SUN=new WeekDay(){
public WeekDay nextDay()//覆盖父类的抽象方法,建立子类对象调用
{
return MON;
}
};
public final static WeekDay MON=new WeekDay(){
public WeekDay nextDay()
{
return SUN;
}
};
public abstract WeekDay nextDay();
public String toString()
(
return this==SUN?"SUN":"MON";
)
}
public class EnumTest
{
public static void main(String[] args)
{
WeekDay weekDay=WeekDay.MON;
System.out.println(weekDay.nextDay());
}
}
|