Can we define an enum inside a class in Java?

JavaServer Side ProgrammingProgramming

Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax

enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Example

Live Demo

public class EnumerationExample {
   enum Enum {
      Mango, Banana, Orange, Grapes, Thursday, Apple
   }
   public static void main(String args[]) {
      Enum constants[] = Enum.values();
      System.out.println("Value of constants: ");  
      for(Enum d: constants) {
         System.out.println(d);
      }
   }
}

Output

Value of constants:
Mango
Banana
Orange
Grapes
Thursday
Apple

Example

Live Demo

enum Vehicles {
   //Declaring the constants of the enum
   ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
   int i; //Instance variable
   Vehicles() { //constructor
   }  
   public void enumMethod() { //method
      System.out.println("Current value: "+Vehicles.this);
   }
}
public class Sam{
   public static void main(String args[]) {
      Vehicles vehicles[] = Vehicles.values();
      for(Vehicles veh: vehicles) {
         System.out.println(veh);
      }
      vehicles[3].enumMethod();      
   }  
}

Output

ACTIVA125
ACTIVA5G
ACCESS125
VESPA
TVSJUPITER
Current value: VESPA
raja
Published on 08-Feb-2021 11:23:50
Advertisements