1. 枚举类型的定义范围:
1)枚举类型可以是单独的一个class文件
/*** This enum is declared in the Season.java file.*/
public enumSeason {
WINTER,
SPRING,
SUMMER,
FALL
}
2)同样可以定义在其他类里面
public classDay {privateSeason season;publicString getSeason() {returnseason.name();
}public voidsetSeason(String season) {this.season =Season.valueOf(season);
}/*** This enum is declared inside the Day.java file and
* cannot be accessed outside because it's declared as private.*/
private enumSeason {
WINTER,
SPRING,
SUMMER,
FALL
}
}
3)但是不能定义在构造方法或普通方法体类,会报编译错误
public classDay {/*** Constructor*/
publicDay() {//Illegal. Compilation error
enumSeason {
WINTER,
SPRING,
SUMMER,
FALL
}
}public voidaSimpleMethod() {//Legal. You can declare a primitive (or an Object) inside a method. Compile!
int primitiveInt = 42;//Illegal. Compilation error.
enumSeason {
WINTER,
SPRING,
SUMMER,
FALL
}
Season season=Season.SPRING;
}
}
2.枚举类型注意事项
1)枚举中的元素不能重复
public enumSeason {
WINTER,
WINTER,//Compile Time Error : Duplicate Constants
SPRING,
SUMMER,
FALL
}
2)枚举中定义的常量默认都是public static final 修饰
3) jdk1.6及以下switch参数不能直接传递字符串,但可以可以使用enum类型
public static voidenumSwitchExample(Season s) {switch(s) {caseWINTER:
System.out.println("It's pretty cold");break;caseSPRING:
System.out.println("It's warming up");break;caseSUMMER:
System.out.println("It's pretty hot");break;caseFALL:
System.out.println("It's cooling down");break;
}
}
4)枚举类型中不能有public构造方法,但可以用私有的构造方法(默认为私有的)
public enumCoin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25); //usual names for US coins//note that the above parentheses and the constructor arguments match
private intvalue;
Coin(intvalue) {this.value =value;
}public intgetValue() {returnvalue;
}
}
5)枚举中可以有抽象方法,其中每一个类型可以单独实现该抽象方法
enumAction {
DODGE {public booleanexecute(Player player) {returnplayer.isAttacking();
}
},
ATTACK {public booleanexecute(Player player) {returnplayer.hasWeapon();
}
},
JUMP {public booleanexecute(Player player) {return player.getCoordinates().equals(new Coordinates(0, 0));
}
};public abstract booleanexecute(Player player);
}
还有一些其他的用法,没有一 一列举,可以参考地址:https://stackoverflow.com/documentation/java/155/enums#t=201708250625516795921;