Java如何使用Enum构造函数和方法?

在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.

上一篇: Java方法 下一篇: Java文件