public enum Gender {
//枚举值都是大写字母
//枚举值1, 枚举值2, ...
MAN, WOMEN;
}
public class Person {
private String name;
//private String sex;
private Gender sex; //性别使用枚举表示,可以规范取值
public Person(String name, Gender sex) {
this.name = name;
this.sex = sex;
}
}
public class Test {
public static void main(String[] args) {
//Person p1 = new Person("张三","男");
//Person p2 = new Person("张三","男人");
//Person p3 = new Person("张三","男生");
Person p1 = new Person("张三", Gender.MAN);
Person p2 = new Person("李四", Gender.WOMEN);
}
}
反编译
//季节
public enum Season {
SPRING , //春
SUMMER, //夏
AUTUMN, //秋
WINTER; //冬
}
/*
反编译代码
public final class Season extends Enum{
public static final Season SPRING = new Season("SPRING", 0);
public static final Season SUMMER = new Season("SUMMER", 1);
public static final Season AUTUMN = new Season("AUTUMN", 2);
public static final Season WINTER = new Season("WINTER", 3);
private Season(String s, int i){
super(s, i);
}
}
结论
结论:
枚举类编译后本质是final修饰的java类,并且继承了java.lang.Enum类。
枚举类的构造方法都是private修饰的,所以枚举类无法在外部创建对象。
每个枚举值都是该类的对象,并且都是public static final修饰的。
枚举本质是一个java类,所以枚举中可以有成员变量、成员方法、构造方法等成分