Java中的枚举(枚举)是一种存储一组常量值的数据类型。您可以使用枚举来存储固定值,例如一周中的天,一年中的月等。
您可以使用关键字enum定义枚举,后跟枚举的名称为-
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
在声明枚举时,您需要牢记以下几点:
建议使用所有大写字母将常量的名称写为-
public class EnumerationExample { enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } }
您可以在类内定义一个枚举。
public class EnumerationExample { enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } public static void main(String args[]) { Days constants[] = Days.values(); System.out.println("Value of constants: "); for(Days d: constants) { System.out.println(d); } } }
输出结果
Value of constants: SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY
您可以在枚举内包含变量和方法,如下所示:
enum Vehicles { Activa125, Activa5G, Access125, Vespa, TVSJupiter; int i; //variable Vehicles() { //constructor System.out.println("Constructor of the enumeration"); } public void enumMethod() {//method System.out.println("This is a method of enumeration"); } }
但是,如果您编写任何其他内容,则枚举的第一行必须始终是常量的声明,它会产生编译时错误-
enum Vehicles { int i; //variable Activa125, Activa5G, Access125, Vespa, TVSJupiter; Vehicles() { //constructor System.out.println("Constructor of the enumeration"); } public void enumMethod() {//method System.out.println("This is a method of enumeration"); } }
Vehicles.java:1: error: <identifier> expected enum Vehicles { ^ Vehicles.java:2: error: ',', '}', or ';' expected int i; //variable ^ Vehicles.java:3: error: <identifiergt; expected Activa125, Activa5G, Access125, Vespa, TVSJupiter; ^ 3 errors
您不能在方法内部定义枚举。如果尝试这样做,则会生成一个编译时错误,提示“枚举类型一定不能是本地的”。
public class EnumExample{ public void sample() { enum Vehicles { Activa125, Activa5G, Access125, Vespa, TVSJupiter; } } }
EnumExample.java:3: error: enum types must not be local enum Vehicles { ^ 1 error