Java Examples - Using Enum Constructor and Methods

Java 实例Java Examples

The following example demonstrates the use of Enum constructors and methods:

Main.java file

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("Price of all cars:"); for (Car c : Car.values()) System.out.println(c + "Costs" + c.getPrice() + "thousand dollars."); } }

Running the above code produces the following output:

所有汽车的价格:
lamborghini 需要 900 千美元。
tata 需要 2 千美元。
audi 需要 50 千美元。
fiat 需要 15 千美元。
honda 需要 12 千美元。

Java 实例Java Examples

Other extensions