本帖最后由 小黑子 于 2014-10-12 20:37 编辑
在看高新技术视频。张老师在:13_用普通类模拟枚举类的实现原理.avi 中
在EnumTest.java中这样写的,这没有什么疑惑。
- package cn.itheima.day1;
- public class EnumTest {
- public static void main(String[] args) {
- WeekDay wk1 = WeekDay.SUN;
- System.out.println(wk1.nextDay());
- }
- }
复制代码 然后第一次在WeekDay.java中是这样写,也没什么疑惑
- package cn.itheima.day1;
- public class WeekDay {
- private WeekDay(){}
-
- public static final WeekDay SUN = new WeekDay();
- public static final WeekDay MON = new WeekDay();
- public static final WeekDay TUE = new WeekDay();
-
- public WeekDay nextDay()
- {
- if(this==SUN)
- {
- return MON;
- }else if(this==MON)
- {
- return TUE;
- }else
- {
- return SUN;
- }
- }
- public String toString()
- {
- if(this==SUN)
- return "SUN";
- if(this==MON)
- return "MON";
- if(this==TUE)
- return "TUE";
- return null;
- }
- }
复制代码
可是第二次在WeekDay.java中是这样写的,我就不懂了。
- package cn.itheima.day1;
- public abstract class WeekDay {
- private WeekDay(){}
-
- public static final WeekDay SUN = new WeekDay(){
- public WeekDay nextDay()
- {
- return MON;
- }
- };
- public static final WeekDay MON = new WeekDay(){
- public WeekDay nextDay()
- {
- return TUE;
- }
- };
- public static final WeekDay TUE = new WeekDay(){
- public WeekDay nextDay()
- {
- return SUN;
- }
- };
-
- public abstract WeekDay nextDay();
- /*
-
- public WeekDay nextDay()
- {
- if(this==SUN)
- {
- return MON;
- }else if(this==MON)
- {
- return TUE;
- }else
- {
- return SUN;
- }
- }
- */
- public String toString()
- {
- if(this==SUN)
- return "SUN";
- if(this==MON)
- return "MON";
- if(this==TUE)
- return "TUE";
- return null;
- }
- }
复制代码
在这种方法中,用的匿名内部类。匿名内部类,我也知道,毕老师的视频中有讲。但是好像没讲这种形式。不是说匿名内部有个前提条件:必须继承一个父类或实现一个接口吗?? 可是这里没有继承啊或者实现啊!!
第二:为什么要在类中定义一个 public abstract WeekDay nextDay(); ???
第三:张老师说public static final WeekDay SUN = new WeekDay(){ ... }; 中的new WeekDay(){}; 是WeekDay的子类。为什么是子类呢?=================================================================
PS:刚把毕老师的匿名内部类的视频又看了一遍,明白了:lol:lol:lol
|