Enum in a class in Java



Yes, we can create Enum in a class in Java.

Set the enum inside the class. Here, we have an Enum with four constants −

enum Devices {
LAPTOP, MOBILE, TABLET, DESKTOP;
}

Now, create objects inside the main() method −

Devices d = Devices.MOBILE;
System.out.println(d);
d = Devices.DESKTOP;
System.out.println(d);

The following is the complete example −

Example

 Live Demo

public class Demo {
   enum Devices {
      LAPTOP, MOBILE, TABLET, DESKTOP;
   }
   public static void main(String[] args) {
      Devices d = Devices.MOBILE;
      System.out.println(d);
      d = Devices.DESKTOP;
      System.out.println(d);
      d = Devices.TABLET;
      System.out.println(d);
   }
}

Output

MOBILE
DESKTOP
TABLET
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements