在 Java 中实现枚举的 Switch 语句

java 8object oriented programmingprogramming

Java 中的枚举包含一组固定的常量。它们可以包含字段、构造函数和方法。这增强了 Java 的类型安全性。

以下是在 Java 中实现枚举的 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!

相关文章