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