程式语言中的一种数据类型 ENUM( 二 )

接口方法实现列举一个enum是定义一组值的对象,它可以包括零个或多个值成员.它是属于enum类型的,一个enum对象中不可有两个或多个相同的属性或值.在此之前的java程式设计师一般是 用接口的方法实现列举的,如 :public interface Season{static winter = 0;static spring = 1;//etc..}Enum实例引入了enum的java的列举的编写方便了许多,只须定义一个enum型的对象.enum对象的值都会自动获得一个数字值,从0开始,依次递增.看一个比较简单的enum实现的例子:EnumDemo.javapackage net.javagarage.enums;/*We can loop over the values we put into the enumusing the values() method.Note that the enum Seasons is compiled into aseparate unit,called EnumDemo$Seasons.class*/public class EnumDemo{/*declare the enum and add values to it.note that,like in#,we don't sea‘;’toend this statement and we use commas to separate the values*/private enum Seasons{winter,spring,summer,fall}//listthevaluespublic static void main(String[]args){for(Seasons s:Seasons.values()){System.out.println(s);}}}运行上述代码你会得到 以下结果:winterspringsummerfallEnum的属性调用:下面的代码展示了调用enum对象的方法,这也是它通常的用法:package net.javagarage.enums;/*File:EnumSwitch.javaPurpose:show how to switch against the values in an enum.*/public class EnumSwitch{private enum Color{red,blue,green}//list the valuespublic static void main(String[]args){//refer to the qualified valuedoIt(Color.red);}/*note that you switch against the UNQUALIFIED name.that is,"caseColor.red:"is acompiler error*/private static void doIt(Color c){switch(c){case red:System.out.println("valueis"+Color.red);break;case green:System.out.println("valueis"+Color.green);break;case blue:System.out.println("valueis:"+Color.blue);break;default:System.out.println("default");}}} 为Enums添加属性和方法enums也可以象一般的类一样添加方法和属性,你可以为它添加静态和非静态的属性或方法,这一切都象你在一般的类中做的那样.就是这幺的简单.但是有一点是需要注意的,那就是enums的值列表必须紧跟在enum声明,不然编译时将会出错.Enums构造函式:和类一样enums也可以有自己的构造函式儘管enums有这幺多的属性,但并不是用的越多越好,如果那样还不如直接用类来的直接.enums的优势在定义int最终变数仅当这些值有一定特殊含义时.但是如果你需要的是一个类,就定义一个类,而不是enum.