解释在 Java 中使用枚举的限制?


Java 中的枚举 (enum) 是一种数据类型,用于存储一组常量值。您可以使用枚举来存储固定值,例如一周中的几天,一年中的月份等。

您可以使用关键字 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

更新于:2019年7月30日

679 次查看

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.