Enum constructor trong Java



Miêu tả vấn đề

Cách sử dụng enum constructor, biến instance và phương thức trong Java?

Giải pháp

Ví dụ sau khởi tạo enum bởi sử dụng một constructor và phương thức getPrice() và hiển thị giá trị của enum trong Java.

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.");
   }
}

Kết quả

Code trên sẽ cho kết quả sau:

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.

phuong-thuc_trong_java.jsp