枚举
自定义类实现枚举
// 1.将构造器私有化,防止直接new
// 2.去掉set方法,防止属性被修改
// 3.再Season内部直接创建固定的对象
// 4.优化,可以加入final修饰符
// 5.可以提供get方法,但不能提供set方法
public class Enumeration_02 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
System.out.println(Season.SUMMER);
System.out.println(Season.AUTUMN);
System.out.println(Season.WINTER);
}
}
class Season {
private String name;
private String desc;//描述
public static final Season SPRING = new Season("春天", "温暖");
public static final Season WINTER = new Season("冬天", "寒冷");
public static final Season SUMMER = new Season("夏天", "炎热");
public static final Season AUTUMN = new Season("秋天", "凉爽");
private Season(String name, String desc) {
this.name = name;
this.desc = desc;
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
enum关键字实现枚举
public class Enumeration_03 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
System.out.println(Season.SUMMER);
System.out.println(Season.AUTUMN);
System.out.println(Season.WINTER);
System.out.println(Season.What);
}
}
enum Season {
// 1.使用enum代替class
// 2.public static final Season SPRING = new Season("春天","温暖")
// 直接使用SPRING("春天", "温暖")替代
// 常量名(实参列表)
// 3.如果有多个常量(对象),使用“,”间隔即可
// 4.如果使用enum来实现枚举,要求将定义的常量对象写在前面
// 5.如果使用的是无参构造器,创建常量对象则可以省略()
SPRING("春天", "温暖"),
SUMMER("夏天", "火热"),
AUTUMN("秋天","凉爽"),
WINTER("冬天","寒冷"),
What;
private String name;
private String desc;//描述
Season() {
System.out.println("无参构造器");
}
private Season(String name, String desc) {
this.name = name;
this.desc = desc;
}
public String getName() {
return name;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
注意事项
1.使用enum关键字开发一个枚举时,默认会继承Enum类[ 通过javap可知]