Home  >  Article  >  Java  >  Java Example - Use of Enum (enumeration) constructor and methods

Java Example - Use of Enum (enumeration) constructor and methods

黄舟
黄舟Original
2017-02-16 10:31:051407browse

The following example demonstrates the use of Enum (enumeration) constructor and method:

/*
 author by w3cschool.cc
 Main.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("所有汽车的价格:");
      for (Car c : Car.values())
      System.out.println(c + " 需要 " 
      + c.getPrice() + " 千美元。");
   }}

The output result of running the above code is:

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

The above is the Java example - Enum ( Enumeration) constructor and method usage, please pay attention to the PHP Chinese website (m.sbmmt.com) for more related content!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn