我们可以在Java枚举中包含变量和方法吗?

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

您可以使用关键字enum定义枚举,后跟枚举的名称为-

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

枚举中的方法和变量

枚举类似于类,您可以在其中包含变量,方法和构造函数。枚举中仅允许使用具体方法。

示例

在下面的示例中,我们定义一个名称为Vehicles的枚举,并在其中声明五个常量。

除了它,我们还有一个构造函数,实例变量和实例方法。

enum Vehicles {
   //声明枚举的常量
   ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
   //枚举的实例变量
   int i;
   //枚举的构造方法
   Vehicles() {}
   //枚举的方法
   public void enumMethod() {
      System.out.println("This is a method of enumeration");
   }
}
public class EnumExample{
   public static void main(String args[]) {
      Vehicles vehicles[] = Vehicles.values();
      for(Vehicles veh: vehicles) {
         System.out.println(veh);
      }
      System.out.println("Value of the variable: "+vehicles[0].i);
      vehicles[0].enumMethod();
   }
}

输出结果

ACTIVA125
ACTIVA5G
ACCESS125
VESPA
TVSJUPITER
Value of the variable: 0
This is a method of enumeration

示例

在下面的Java示例中,我们声明5个带有值的常量,我们有一个实例变量来保存常量的值,有一个参数化的构造函数对其进行初始化,以及一个getter方法来获取这些值。

import java.util.Scanner;
enum Scoters {
   //带值的常量
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
   //实例变量
   private int price;
   //Constructor to initialize the 实例变量
   Scoters (int price) {
      this.price = price;
   }
   //静态显示价格的方法
   public static void displayPrice(int model){
      Scoters constants[] = Scoters.values();
      System.out.println("Price of: "+constants[model]+" is "+constants[model].price);
   }
}
public class EnumerationExample {
   public static void main(String args[]) {
      Scoters constants[] = Scoters.values();
      System.out.println("Value of constants: ");
      for(Scoters d: constants) {
         System.out.println(d.ordinal()+": "+d);
      }
      System.out.println("Select one model: ");
      Scanner sc = new Scanner(System.in);
      int model = sc.nextInt();
      //Calling the static 枚举的方法
      Scoters.displayPrice(model);
   }
}

输出结果

Value of constants:
0: ACTIVA125
1: ACTIVA5G
2: ACCESS125
3: VESPA
4: TVSJUPITER
Select one model:
2
Price of: ACCESS125 is 75000