在 Java 中實現 Switch on Enum


Java 中的 Enum 包含一組固定的常量。它們可以有欄位、建構函式和方法。它增強了 Java 中的型別安全性。

以下示例在 Java 中對 Enumeration 實現了 Switch 語句 -

示例

 線上演示

public class Demo {
   public static void main(String[] args) {
      Laptop l = Laptop.Inspiron;
      switch(l){
         case Inspiron:
         System.out.println("Laptop for home and office use!");
            break;
         case XPS:
          System.out.println("Laptop for the ultimate experience!");
            break;
         case Alienware:
          System.out.println("Laptop for high-performance gaming");
            break;
      }
   }
}
enum Laptop {
      Inspiron, XPS, Alienware;
}

輸出

Laptop for home and office use!

更新於: 2020 年 6 月 29 日

179 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
Advertisement
© . All rights reserved.