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(); }
枚举可实现接口,并能够在每一个值上提供特定的实现。