Java enum

enum


概述1

1. 创建枚举类型要使用 enum 关键字
2. 隐含了所创建的类型都是 Java.lang.Enum 类的子类(java.lang.Enum 是一个抽象类)
3. 构造函数中简单来说就是枚举类型中的枚举值都会对应调用一次构造函数
4. 枚举中的构造函数是私有类,无法在外面创建enum的子类
5. 枚举类对象不可变,父类不可被子类继承,方法不会被重写
6. 枚举值默认static(静态类常量) ,会为每个类常量增加一个构造函数
7. 枚举类型比较:equals 方法与 == 方法相同

示例

public enum Color {
    /**
     * 红色,枚举值必须有文档注释
     */
    RED("red","红色"), // 枚举值列举以,分隔
    /**
     * 绿色,枚举值必须有文档注释
     */
    GREEN("green","绿色"); // 枚举值列举以;结束

    private String color ;
    private String desc ;

    Color(String color , String desc){ // 构造方法无需添加 private ,默认私有,外部无法通过构造方法创建对象
        this.color = color;
        this.desc = desc ;
    }

    public String getColor(){ // 需要自定义对外暴露的属性
        return this.getColor();
    }

    public String getDesc(){
        return this.getDesc();
    }

    public static void main(String[] args) {
        System.out.println(RED.getColor()); // 枚举类中的方法默认带有 static 修饰
        System.out.println(GREEN.getDesc());
    }
}

equals 与 == 等价

    // 枚举类型比较 
    public static void main(String[] args) {
        System.out.println(ColorEnum.RED.equals(ColorEnum.RED)); // true 
        System.out.println(ColorEnum.RED == ColorEnum.RED); // true
    }
  • Enum.java 源码中 equals 与 == 等价
   /**
     * Returns true if the specified object is equal to this
     * enum constant.
     *
     * @param other the object to be compared for equality with this object.
     * @return  true if the specified object is equal to this
     *          enum constant.
     */
    public final boolean equals(Object other) {
        return this==other;
    }

  1. java枚举类的构造函数实例详解 ↩︎

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值