Java 示例 - 使用 Enum 构造函数、方法
-
问题描述
如何使用枚举构造函数、实例变量和方法? -
解决方案
此示例使用 costructor 和 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.