4. Enumjava
4.1 枚舉的特徵ide
枚舉是類的一種this
枚舉擴展自java.lang.Enumspa
枚舉中每個聲明的值是枚舉類型的一個實例excel
枚舉沒有公共的構造方法code
枚舉中的值都是public static final的接口
枚舉中的值能夠用==或equals()方法判等ip
枚舉實現了java.lang.Comparable接口,能夠經過compareTo()方法進行比較get
枚舉覆寫了toString()方法,返回枚舉中值的名稱編譯器
枚舉提供了valueOf()方法返回枚舉的值(注:valueOf()方法與toString()方法對應,若是改變了toString()方法,請同時修改valueOf()方法)
枚舉定義了一個final的實例方法ordinal(),返回值在枚舉中的整數座標,以0開始(注:通常由其餘輔助設施使用,不直接在代碼中使用)
枚舉定義了values()方法,返回枚舉中定義的全部值(通常在遍歷時使用)
枚舉類型的基本組成元素包括:
enum關鍵字
名稱
除上述基本元素,枚舉類型還能夠:
實現接口
定義變量
定義方法
與值對應的類的定義體
4.3 代碼示例
4.3.1 建立枚舉類型
public enum Grade { A, B, C, D, F, INCOMPLETE };
這是枚舉類型的最基本的建立方式,也是最經常使用的方式。
4.3.2 內聯方式(inline)建立
枚舉還能夠經過內聯方式建立:
public class Report { public static enum Grade1 {A, B, C}; // the "static" keyword is redundant. public enum Grade2 {A, B, C}; }
注意static關鍵字是默認的,不需顯式聲明。
4.3.3 定義變量和方法
public enum Grade { // enum values must be at the top. A("excellent"), B("good"), C("pass"), F("fail"); // there is a semicolon. // field private String description; // the constructor must be private(the compiler set it by default) // so it can be omitted. private Grade(String description) { this.description = description; } // method public String getDescription() { return this.description; } }
枚舉的值定義在最上方,最後一個值的定義由";"結束。
構造器必須爲private,由編譯器自動添加,不需顯式聲明。
4.3.4 與值對應的類的定義體
public enum Grade implements Descriptable { A("excellent") { @Override public String getDescription() { return "congratulations! you got an excellent grade!"; } }, B("good") { @Override public String getDescription() { return "well done! your grade is good!"; } }, C("pass") { @Override public String getDescription() { return "you passed the exam."; } }, F("fail") { @Override public String getDescription() { return "sorry, you failed the exam!"; } }; private String description; Grade(String description) { this.description = description; } } public interface Descriptable { String getDescription(); }
枚舉可實現接口,並能夠在每一個值上提供特定的實現。