/**//* We can loop over the values we put into the enum using the values() method. Note that the enum Seasons is compiled into a separate unit, called EnumDemo$Seasons.class */ publicclass EnumDemo ...{ /**//*declare the enum and add values to it. note that, like in C#, we don't use a ; to end this statement and we use commas to separate the values */ privateenum Seasons ...{ winter, spring, summer, fall } //list the values publicstaticvoid main(String[] args) ...{ for (Seasons s : Seasons.values())...{ System.out.println(s); } } }
运行上述代码你回得到 以下结果:
winter spring summer fall Enum的属性调用:
下面的代码展示了调用enum对象的方法,这也是它通常的用法:
package net.javagarage.enums; /**//* File: EnumSwitch.java Purpose: show how to switch against the values in an enum. */ publicclass EnumSwitch ...{ privateenum Color ...{ red, blue, green } //list the values publicstaticvoid main(String[] args) ...{ //refer to the qualified value doIt(Color.red); } /**//*note that you switch against the UNQUALIFIED name. that is, "case Color.red:" is a compiler error */ privatestaticvoid doIt(Color c)...{ switch (c) ...{ case red: System.out.println("value is "+ Color.red); break; case green: System.out.println("value is "+ Color.green); break; case blue: System.out.println("value is : "+ Color.blue); break; default : System.out.println("default"); } } }
Enum是enumeration(列举)的简写形式,包含在java.lang包中.熟悉C, C++, C#, 或 Pascal人应该对列举有所了解,先看个例子: public enum Season ...{ winter, spring, summer, fall }一个enum是定义一组值的对象,它可以包括零个或多个值成员.它是属于enum类型的,一个enum对象中不可有两个或