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