JAVA enum枚舉類型的使用,javaenum枚舉類型
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;