public class Enumeration {
private String name;
private String desc;
//1.构造器私有化
private Enumeration(String name, String desc) {
this.name = name;
this.desc = desc;
}
//2.创建一组对象
public static final Enumeration SUMMER = new Enumeration("夏天","热");
public static final Enumeration SPRING = new Enumeration("春天","温暖");
public static final Enumeration AUTUMN = new Enumeration("秋天","凉爽");
public static final Enumeration WINTER = new Enumeration("冬天","寒冷");
public static int count = 0;
static {
//以此证明类加载一次
count++;
System.out.println("count"+count);
}
}
class T2{
public static void main(String[] args) {
Enumeration autumn = Enumeration.AUTUMN;
Enumeration spring = Enumeration.SPRING;
Enumeration summer = Enumeration.SUMMER;
Enumeration winter = Enumeration.WINTER;
}
}
public class Enumeration02 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
}
}
//1.使用关键字enum替代class
//2.public static final Season SPRING = new Enumeration("春天","温暖"); 等价于 SPRING("春天","温暖")
//Season.SPRING = Season.AUTUMN;会报错测试出是由public static final修饰的
enum Season{
//3.如果有多个常量(对象)使用,使用,间隔
//4.如果使用enum来实现枚举,要求将定义常量对象,写在前面
//5.如果我们使用的是无参构造器,则实参列表和小括号可以省略
// S相等于 public static final Season = new S();
S,SPRING("春天","温暖"),SUMMER("夏天","炎热"),AUTUMN("秋天","凉爽"),WINTER("冬天","寒冷");
private String name;
private String desc;
private Season(){
}
private Season(String name, String desc) {
this.name = name;
this.desc = desc;
}
static {
System.out.println("测试使用枚举类中对象类是否会被加载");
}
}
javap 类名.class反编译之后的结构
说明:使用关键字enum时,会隐式继承Enum类,这样我们就可以使用Enum类相关的方法。[看下源码定义]
public abstract class Enum