A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 翟宝海 中级黑马   /  2013-6-3 18:19  /  1284 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在java中,一个类中如果有抽象方法,那么这个类就是抽象类。

  1. public enum TrafficLamp
  2.         {
  3.                 RED{
  4.                         public  TrafficLamp nextLamp()
  5.                         {
  6.                                 return GREEN;
  7.                         }
  8.                 },
  9.                 GREEN{
  10.                         public  TrafficLamp nextLamp()
  11.                         {
  12.                                 return YELLOW;
  13.                         }
  14.                 },
  15.                 YELLOW{
  16.                         public  TrafficLamp nextLamp()
  17.                         {
  18.                                 return RED;
  19.                         }
  20.                 };
  21.                 public abstract TrafficLamp nextLamp();//抽象方法
  22.         }
复制代码
既然枚举也是一个类,为什么它里面有了抽象方法,它不需要被abstract修饰,也成为抽象类呢?

评分

参与人数 1技术分 +1 收起 理由
Sword + 1

查看全部评分

2 个回复

倒序浏览
因为enum 类 是不能被继承的,也不能new 的,而abstract 修饰 一个类是为了声明,该类需要被继承,不能直接new。
因此如果用abstract 来修饰enum 类,其实就是一种矛盾。
回复 使用道具 举报
亲,因为Enum定义的时候就是abstract,在程序开发中,经常用到这种java数据类型,就把enum这个关键字做为特殊的数据类型。在eclipse中,选择enum关键字,在点击电脑右键,进入到enum的源码就会发现你要的秘密了哦。附enum源码
  1. public abstract class Enum<E extends Enum<E>>
  2.         implements Comparable<E>, Serializable {
  3.     /**
  4.      * The name of this enum constant, as declared in the enum declaration.
  5.      * Most programmers should use the {@link #toString} method rather than
  6.      * accessing this field.
  7.      */
  8.     private final String name;

  9.     /**
  10.      * Returns the name of this enum constant, exactly as declared in its
  11.      * enum declaration.
  12.      *
  13.      * <b>Most programmers should use the {@link #toString} method in
  14.      * preference to this one, as the toString method may return
  15.      * a more user-friendly name.</b>  This method is designed primarily for
  16.      * use in specialized situations where correctness depends on getting the
  17.      * exact name, which will not vary from release to release.
  18.      *
  19.      * @return the name of this enum constant
  20.      */
  21.     public final String name() {
  22.         return name;
  23.     }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马