Java中的枚举中可以有变量和方法吗?
Java 中的枚举 (enum) 是一种存储常量值的数据类型。你可以使用枚举来存储固定值,例如一周中的天数、一年的月份等。
使用关键字 enum 后跟枚举的名称来定义枚举,如下所示 −
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}枚举中的方法和变量
枚举类似于类,你可以在枚举中拥有变量、方法和构造函数。在枚举中只允许使用具体方法。
示例
在以下示例中,我们定义了一个名为 Vehicles 的枚举,并在其中声明了五个常量。
此外,我们还有一个构造函数、实例变量和一个实例方法。
enum Vehicles {
//Declaring the constants of the enum
ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
//Instance variable of the enum
int i;
//Constructor of the enum
Vehicles() {}
//method of the enum
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 {
//Constants with values
ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
//Instance variable
private int price;
//Constructor to initialize the instance variable
Scoters (int price) {
this.price = price;
}
//Static method to display the 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 method of the enum
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
广告
数据结构
计算机网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP