课时113:定义枚举结构
摘要:本内容为定义枚举结构的介绍。
1. 枚举的定义
2. 在枚举类中定义其它的结构.
3. 让枚举实现接口
4.观察枚举中定义抽象方法
01. 枚举的定义
枚举本身属于一种多例设计模式,在一个类中可以定义的结构非常多,例如:构造方法、普通方法、属性等,那么这些内容在枚举类中可以直接定义,但是需要注意枚举类中定义的构造方法不能采用非私有化定义( Public 无法使用)。
02.在枚举类中定义其它的结构.
Enum Color { // 枚举类 RED ,GREEN,BLUE ; //实例化对象 Private string title ; // 定义属性 }
运行后发现错误,接着将代码中定义属性与实例化对象交换位置
Enum Color { // 枚举类 Private string title ; // 定义属性 RED ,GREEN,BLUE ; //实例化对象 }
结论:枚举对象要写在首行
Enum Color { // 枚举类 RED (“红色”) ,GREEN(“绿色”),BLUE(“蓝色”) ; //枚举对象要写在首行,多例设计中的每个实例都是常量,这是用大写字母的主要原因。 Private string title ; // 定义属性 Private Color(string title) { This.title = title ; } Public string tostring() { Return this.title ; } } Puolic class JavaDemo { Public static void main(string args[]) { For (Color c:Color.values()) { System.out.println(c.ordinal() + “-”+c.name() + “-”+ c); } } }
程序执行结果:
结论:本程序在简化程度上一定要远远高于多例设计模式(多例设计模式要写更多属性的定义,而枚举相对而言简单许多)。除了这种基本的结构之外,在枚举类中也可以实现接口的继承。
03.让枚举实现接口
Interface IMessage { Public string getMessage() ; } Enum Color Interface IMessage { // 枚举类 RED (“红色”) ,GREEN(“绿色”),BLUE(“蓝色”) ; //枚举对象要写在首行 Private string title ; // 定义属性 Private Color(string title) { This.title = title ; } Public string tostring () { Return this.title ; } Public string getmessage () { //覆写方法 Return this.title ; } } Puolic class JavaDemo { Public static void main(string args []) { IMessage msg = Color.RED; System.out.println(msg.getMessage()); } }
执行代码结果:成功
这个结构跟正常类的结构非常相似,在枚举类里它可以直接定义抽象方法,并且要求每一个枚举对象都要独立覆写此抽象方法。
04.观察枚举中定义抽象方法
Enum Color { // 枚举类 RED (“红色”){ Public string getmessage() { Return this.tostring(); } } ,GREEN(“绿色”){ Public string getmessage() { Return this.tostring() ; } },BLUE(“蓝色”){ Public string getmessage() { Return this .tostring(); } } ; //枚举对象要写在首行 Private string title ; // 定义属性 Private Color(string title) { This.title = title ; } Public string tostring () { Return this.title ; } Public abstract string getmessage () ; } Puolic class JavaDemo { Public static void main(string args []) { System.out.println(Color.RED.getMessage()); } }
运行成功
结论:发现枚举的定义是非常灵活的,但是在实际的使用之中,枚举更多情况下建议使用它的正确用法(定义一个实例对象即可)。