Java:枚举类 enumerate(包含父类Enum源码)

目录

枚举类

1.为什么我们需要枚举类

2.如何自定义一个枚举类

     两种方式

3.为什么用关键词"enum"自定义的枚举类不能继承其他类?

4.Enum父类常用的方法(附加源码)


枚举类

1.为什么我们需要枚举类

  • 当一个类可以被创建的对象有明确的限定时,我们更倾向于使用枚举类,比如创建一个类来表示季节时,我们可以很明确季节只能有春天,夏天,秋天,冬天这四个对象实例,因此我们倾向于使用枚举类来避免一些奇怪的对象实例产生(如果你想,季节都可以有今天,明天和昨天.).

2.如何自定义一个枚举类

     两种方式

     1.创建类并在类中创建静态公开对象,私有化构造器,并不提供set()相关方法:

class Season {
    private String name;
    public static final Season SPRING = new Season("春天");
    public static final Season SUMMER = new Season("夏天");
    public static final Season AUTUMN = new Season("秋天");
    public static final Season WINTER = new Season("冬天");
    private Season(String name){
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

     2. 用关键词"enum"自定义枚举类:

        注意:1.定义常量变量要放在最前面,且默认被 public static final 修饰;

                2.如果有多个变量用" , "间隔;

                3.无参构造可省略();

enum Season {
    SPRING("春天"),SUMMER("夏天"),AUTUMN("秋天"),WINTER("冬天"),SEASON;
    private String name;
    private Season(String name){
        this.name = name;
    }
    private Season(){}
    public String getName() {
        return name;
    }
}

3.为什么用关键词"enum"自定义的枚举类不能继承其他类?

  • 因为用关键词"enum"自定义的枚举类默认继承了Enum这个父类;
  • 虽然用关键词"enum"自定义的枚举类无法继承其他类,但是仍可以通过实现接口来对单继承体系进行一个补充;

4.Enum父类常用的方法(附加源码)

  • toString():返回当前对象名,子类可以重写
    /**
     * Returns the name of this enum constant, as contained in the
     * declaration.  This method may be overridden, though it typically
     * isn't necessary or desirable.  An enum type should override this
     * method when a more "programmer-friendly" string form exists.
     *
     * @return the name of this enum constant
     */
    public String toString() {
        return name;
    }
  • name():返回当前对象名,但是子类无法重写
    /**
     * Returns the name of this enum constant, exactly as declared in its
     * enum declaration.
     *
     * <b>Most programmers should use the {@link #toString} method in
     * preference to this one, as the toString method may return
     * a more user-friendly name.</b>  This method is designed primarily for
     * use in specialized situations where correctness depends on getting the
     * exact name, which will not vary from release to release.
     *
     * @return the name of this enum constant
     */
    public final String name() {
        return name;
    }
  • ordinal():返回当前对象的位置值(编号),默认从0开始
    /**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    public final int ordinal() {
        return ordinal;
    }
  • values():返回当前枚举类中的所有的枚举对象(源码中没有,但是反编译时可以看到)
  • valueOf(): 将字符串转换成该枚举对象,且该字符串的值要和枚举类中的枚举对象中的一个重名,否则会报错
/**
     * Returns the enum constant of the specified enum type with the
     * specified name.  The name must match exactly an identifier used
     * to declare an enum constant in this type.  (Extraneous whitespace
     * characters are not permitted.)
     *
     * <p>Note that for a particular enum type {@code T}, the
     * implicitly declared {@code public static T valueOf(String)}
     * method on that enum may be used instead of this method to map
     * from a name to the corresponding enum constant.  All the
     * constants of an enum type can be obtained by calling the
     * implicit {@code public static T[] values()} method of that
     * type.
     *
     * @param <T> The enum type whose constant is to be returned
     * @param enumType the {@code Class} object of the enum type from which
     *      to return a constant
     * @param name the name of the constant to return
     * @return the enum constant of the specified enum type with the
     *      specified name
     * @throws IllegalArgumentException if the specified enum type has
     *         no constant with the specified name, or the specified
     *         class object does not represent an enum type
     * @throws NullPointerException if {@code enumType} or {@code name}
     *         is null
     * @since 1.5
     */
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                                String name) {
        T result = enumType.enumConstantDirectory().get(name);
        if (result != null)
            return result;
        if (name == null)
            throw new NullPointerException("Name is null");
        throw new IllegalArgumentException(
            "No enum constant " + enumType.getCanonicalName() + "." + name);
    }
  • compareTo():比较两个枚举常量的编号,返回值为两个枚举常量的位置值之差(前减后)
    /**
     * Compares this enum with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     *
     * Enum constants are only comparable to other enum constants of the
     * same enum type.  The natural order implemented by this
     * method is the order in which the constants are declared.
     */
    public final int compareTo(E o) {
        Enum<?> other = (Enum<?>)o;
        Enum<E> self = this;
        if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
            throw new ClassCastException();
        return self.ordinal - other.ordinal;
    }

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YHanJG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值