在Java中,如何使用枚舉構造函數,實例變數和方法??
此示例使用構造函數和getPrice()
方法初始化枚舉並顯示枚舉值。
package com.zaixian;
enum Car2 {
lamborghini(900), tata(2), audi(50), fiat(15), honda(12);
private int price;
Car2(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class UseOfEnumConstructorMethod {
public static void main(String args[]) {
System.out.println("All car prices:");
for (Car2 c : Car2.values())
System.out.println(c + " costs " + c.getPrice()
+ " thousand dollars.");
}
}
執行上面示例代碼,得到以下結果 -
All car prices:
lamborghini costs 900 thousand dollars.
tata costs 2 thousand dollars.
audi costs 50 thousand dollars.
fiat costs 15 thousand dollars.
honda costs 12 thousand dollars.