Java如何使用Enum建構函式和方法?

2019-10-16 22:30:27

在Java中,如何使用列舉建構函式,範例變數和方法??

此範例使用建構函式和getPrice()方法初始化列舉並顯示列舉值。

package com.yiibai;

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.