Java如何使枚舉構造函數,實例變量和方法?
如何使用枚舉的構造函數,實例變量和方法?
解決方法
使用構造函數和調用getPrice()方法顯示這個例子中初始化枚舉的值。
enum Car { lamborghini(900),tata(2),audi(50),fiat(15),honda(12); private int price; Car(int p) { price = p; } int getPrice() { return price; } } public class Main { public static void main(String args[]){ System.out.println("All car prices:"); for (Car c : Car.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.