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.