枚舉類型在JDK 5時引入。java
enum WeekEnum { MONDAY, TUESDAY, WEDNESDAY, THURDAY, FRIDAY, SATURDAY, SUNDAY }
Java的枚舉類java.lang.Enum中,有:
|--private final String name;(定義時可表意的標識符)
|--private final int ordinal;(序數,從0開始)
|--及對應的獲取方法。this
public class Enum1Common { enum WeekEnum { MONDAY, TUESDAY, WEDNESDAY, THURDAY, FRIDAY, SATURDAY, SUNDAY } public static void main(String[] args) { System.out.println("枚舉類型標識符:" + WeekEnum.FRIDAY); for (WeekEnum day : WeekEnum.values()) { System.out.print("直接輸出:" + day);// toString() System.out.print("\t name:" + day.name()); System.out.println("\t ordinal:" + day.ordinal());// 序數 } } }
枚舉類型標識符:FRIDAY
直接輸出:MONDAY name:MONDAY ordinal:0
直接輸出:TUESDAY name:TUESDAY ordinal:1
直接輸出:WEDNESDAY name:WEDNESDAY ordinal:2
直接輸出:THURDAY name:THURDAY ordinal:3
直接輸出:FRIDAY name:FRIDAY ordinal:4
直接輸出:SATURDAY name:SATURDAY ordinal:5
直接輸出:SUNDAY name:SUNDAY ordinal:6code
枚舉類型是一種「特殊的類」,
它能夠有本身的屬性和方法(包括構造方法)。
枚舉類的構造器只能使用private訪問控制符;
若是省略訪問控制符,仍是private。繼承
// 枚舉類也能夠有變量和方法 public class Enum2Member { public static void main(String[] args) { System.out.println(GenderEnum.MALE + ":" + GenderEnum.MALE.getLabel()); // Enum.valueOf():獲取指定枚舉類的枚舉值 GenderEnum g = Enum.valueOf(GenderEnum.class, "FEMALE"); System.out.println(g + ":" + g.getLabel()); } } enum GenderEnum { MALE("男"), FEMALE("女");// 必須第一行 // ---------------------------------- // 枚舉類的屬性值應該使用private final修飾 private final String label; // 枚舉類一旦寫帶參構造器(必須private),列出枚舉值時必須傳參 private GenderEnum(String label) { this.label = label; } public String getLabel() { return this.label; } }
MALE:男 FEMALE:女
// 枚舉類能夠繼承接口 public class Enum3Impl { public static void main(String[] args) { System.out.println(ImplEnum.PLUS.eval(3, 2)); System.out.println(ImplEnum.MINUS.eval(3, 2)); } } interface IOperation { double eval(double x, double y); } enum ImplEnum implements IOperation { PLUS { public double eval(double x, double y) { return x + y; } }, MINUS { public double eval(double x, double y) { return x - y; } } }
5.0 1.0
枚舉類自己能夠定義抽象方法,由各枚舉值實現。接口
// 枚舉類能夠定義「抽象方法」,並由枚舉值實現 public class Enum4Abstract { public static void main(String[] args) { System.out.println(AbstractEnum.TIMES.eval(3, 2)); System.out.println(AbstractEnum.DIVIDE.eval(3, 2)); } } enum AbstractEnum { TIMES { public double eval(double x, double y) { return x * y; } }, DIVIDE { public double eval(double x, double y) { return x / y; } }; // 定義抽象方法(必須在枚舉值以後定義) // 由各枚舉值 提供 具體實現 public abstract double eval(double x, double y); }
6.0 1.5