黑马程序员技术交流社区

标题: 带抽象方法的枚举 [打印本页]

作者: 思维    时间: 2014-8-12 23:03
标题: 带抽象方法的枚举
本帖最后由 思维 于 2014-8-17 09:07 编辑

求问:为什么带抽象方法的枚举类enum前面不能用abstract修饰?
  1. public class EnumTest1{
  2.         public static void main(String[] args){
  3.                 TrafficLamp red = TrafficLamp.RED;
  4.                 System.out.println(red.nextLamp());
  5.                 System.out.println("时间:"+red.time);
  6.         }
  7.         public enum TrafficLamp{
  8.                 //REN(){...},GREEN(){...},YELLOW()[...};
  9.                 RED(30){
  10.                         public TrafficLamp nextLamp(){
  11.                                 return GREEN;
  12.                         }
  13.                 },
  14.                 GREEN(45){
  15.                         public TrafficLamp nextLamp(){
  16.                                 return YELLOW;
  17.                         }
  18.                 },
  19.                 YELLOW(5){
  20.                         public TrafficLamp nextLamp(){
  21.                                 return RED;
  22.                         }
  23.                 };
  24.                 public abstract TrafficLamp nextLamp();
  25.                 private int time;
  26.                 private TrafficLamp(int time){this.time = time;}
  27.         }
  28. }
复制代码

作者: dftgg    时间: 2014-8-13 10:11
顶一个!~!!
作者: a6511631    时间: 2014-8-13 10:42
public abstract TrafficLamp nextLamp()在每个枚举的元素中不是都实现了吗?抽象类没实现抽象方法,直接抛给调用者去实现。而且,照你这样想,接口里面也有抽象方法,为什么接口前面没有加abstract?
作者: 唕    时间: 2014-8-13 10:46
爱思考的好孩子
作者: 思维    时间: 2014-8-13 10:56
a6511631 发表于 2014-8-13 10:42
public abstract TrafficLamp nextLamp()在每个枚举的元素中不是都实现了吗?抽象类没实现抽象方法,直接抛 ...

主要是这个类中每个枚举元素也被实现了,但是类名前有abstract啊?
  1. public abstract class WeekDay{
  2.         //单例设计模式
  3.         private WeekDay(){}
  4.         public abstract WeekDay nextDay();
  5.         public final static WeekDay SUN = new WeekDay(){
  6.                 public WeekDay nextDay(){
  7.                         return MON;
  8.                 }
  9.         };
  10.         public final static WeekDay MON = new WeekDay(){
  11.                 public WeekDay nextDay(){
  12.                         return SUN;
  13.                 }
  14.         };
  15.         public String toString(){
  16.                 return this == SUN?"SUM":"MON";
  17.         }
  18. }
复制代码

作者: 杨庆雷    时间: 2014-8-13 12:14
你的构造方法是私有的,也就是说不能被其他类继承(本来抽象类就不能被继承),你再写个抽象方法,我觉得没啥意义
作者: 笑轻轻    时间: 2014-8-13 12:24
谢谢楼主分享 学习了
作者: 思维    时间: 2014-8-15 18:24
杨庆雷 发表于 2014-8-13 12:14
你的构造方法是私有的,也就是说不能被其他类继承(本来抽象类就不能被继承),你再写个抽象方法,我觉得没 ...

私有构造方法虽然不能被继承,但是抽象方法可以自我实现,保证元素的唯一性啊;P
作者: 杨庆雷    时间: 2014-8-15 20:14
思维 发表于 2014-8-15 18:24
私有构造方法虽然不能被继承,但是抽象方法可以自我实现,保证元素的唯一性啊 ...

至于为什么不能加abstract,我有一个帖子http://bbs.itheima.com/thread-137234-1-1.html
之前不怎么懂  但这次不会被嘲笑了吧




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2