Explain restrictions on using enum in java?

Java 8Object Oriented ProgrammingProgramming

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.

You can define an enumeration using the keyword enum followed by the name of the enumeration as −

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

Points to keep in mind

You need to keep the following points in mind while declaring an enum −

  • It is recommended to write the name of the constants in all capital letters as −
public class EnumerationExample {
   enum Days {
      SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
   }
}
  • You can define an enum inside a class.

Example

 Live Demo

public class EnumerationExample {
   enum Days {
      Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
   }
   public static void main(String args[]) {
      Days constants[] = Days.values();
      System.out.println("Value of constants: ");
      for(Days d: constants) {
         System.out.println(d);
      }
   }
}

Output

Value of constants:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
  • You can have variables and methods inside an enum as −
enum Vehicles {
   Activa125, Activa5G, Access125, Vespa, TVSJupiter;
   int i; //variable
   Vehicles() { //constructor
      System.out.println("Constructor of the enumeration");
   }
   public void enumMethod() {//method
      System.out.println("This is a method of enumeration");
   }
}

But, the first line of the enum must always be the declaration of constants if you write anything else it generates a compile time error −

enum Vehicles {
   int i; //variable
   Activa125, Activa5G, Access125, Vespa, TVSJupiter;
   Vehicles() { //constructor
      System.out.println("Constructor of the enumeration");
   }
   public void enumMethod() {//method
      System.out.println("This is a method of enumeration");
   }
}

Compile time error

Vehicles.java:1: error: <identifier> expected
enum Vehicles {
   ^
Vehicles.java:2: error: ',', '}', or ';' expected
int i; //variable
^
Vehicles.java:3: error: <identifiergt; expected
Activa125, Activa5G, Access125, Vespa, TVSJupiter;
^
3 errors
  • You cannot define an enum inside a method. If you try to do so it generates a compile time error saying “enum types must not be local”.
public class EnumExample{
   public void sample() {
      enum Vehicles {
         Activa125, Activa5G, Access125, Vespa, TVSJupiter;
      }
   }
}

Compile time error

EnumExample.java:3: error: enum types must not be local
enum Vehicles {
^
1 error
raja
Published on 05-Jul-2019 12:34:30
Advertisements