enum
概述
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;
}