如何使用枚举类:
通常的方式是直接定义一个枚举类,但是如果想一个类定义多个枚举类,可以考虑将枚举类定义为内部类来实现例如:
public class BabyConstants {
public static final int BABY_SEX_BOY = 1;
public static final int BABY_SEX_GIRL = 2;
public static final int BABY_SEX_BOYANDGIRL = 3;
public enum BabySex{
BOY(1, "男"),
GIRL(2, "女");
BabySex(int value, String meaning) {
this.value = value;
this.meaning = meaning;
}
private final int value;
private final String meaning;
public int getValue() {
return this.value;
}
public String getMeaning() {
return this.meaning;
}
public static BabySex valueOf(int value) {
for (BabySex e : BabySex.values()) {
if (e.getValue() == value) {
return e;
}
}
return null;
}
}
public enum Constellation{
BAIYANGZUO(1, "白羊座"),
JINNIUZUO(2, "金牛座"),
SHUANGZIZUO(3, "双子座"),
JUXIEZUO(4,"巨蟹座"),
SHIZIZUO(5,"狮子座"),
CHUNVZUO(6,"处女座"),
TIANCHENGZUO(7,"天秤座"),
TIANXIEZUO(8,"天蝎座"),
SHESHOUZUO(9,"射手座"),
MOJIEZUO(10,"魔羯座"),
SHUIPINGZUO(11,"水瓶座"),
SHUANGYUZUO(12,"双鱼座");
Constellation(int value, String meaning) {
this.value = value;
this.meaning = meaning;
}
private final int value;
private final String meaning;
public int getValue() {
return this.value;
}
public String getMeaning() {
return this.meaning;
}
public static Constellation valueOf(int value) {
for (Constellation e : Constellation.values()) {
if (e.getValue() == value) {
return e;
}
}
return null;
}
}
public enum Animal {
SHU(1, "鼠"),
NIU(2, "牛"),
HU(3, "虎"),
TU(4,"兔"),
LONG(5,"龙"),
SHE(6,"蛇"),
MA(7,"马"),
YANG(8,"羊"),
HOU(9,"猴"),
JI(10,"鸡"),
GOU(11,"狗"),
ZHU(12,"猪");
Animal(int value, String meaning) {
this.value = value;
this.meaning = meaning;
}
private final int value;
private final String meaning;
public int getValue() {
return this.value;
}
public String getMeaning() {
return this.meaning;
}
public static Animal valueOf(int value) {
for (Animal e : Animal.values()) {
if (e.getValue() == value) {
return e;
}
}
return null;
}
}
}
本段代码中既有不可变常量定义的性别,也有通过枚举定义的性别,就平时使用来说还是推荐使用枚举类型