Enums in Java

Enums in java actually means grouping same kind of constants as a one unit/package. Constants which are static and final.
Enums are added as feature from JDK 1.5 and above. Lets get an clear idea of enums from below examples.

class WithoutEnums
 {
     public static final String north = "NORTH";
     public static final String south = "SOUTH";
     public static final String east = "EAST";
     public static final String west = "WEST";
 }
  
 public class MainClass
 {
   public static void main(String[] args)
   {
     System.out.println(WithoutEnums.north);
     System.out.println(WithoutEnums.south);
    System.out.println(WithoutEnums.east);
      System.out.println(WithoutEnums.west);
    }
 }

The above examples is without using the concept of enums.

Lets see how to declare constants using enums.

enum POLES
 {
     NORTH, SOUTH, EAST, WEST;
 }
  
 public class EnumsExample
 {
     public static void main(String[] args)
     {
         POLES d1 = POLES.EAST;
         System.out.println(d1);
  
         POLES d2 = POLES.NORTH;
         System.out.println(d2);
  
         System.out.println(POLES.SOUTH);
  
         System.out.println(POLES.WEST);
     }
 }

Here in the above example we need not create a reference to access the constant, and we can directly access using the enum Class.

Below are the few points need to remember while using Enum class in java.

Enums in java are declared with enum keyword and constants in It is good practice to declare constants with UPPERCASE letters Look at the sample example below:

enum Foods
 {
     CHIPS, FRIES, BREAKFAST;

Duplicates are not allowed in enum constants, it would throw compile time error.

By default each constant declared in enum Class is public static final. As every constant is static, they can be accessed directly using enum name.

Semicolon at the end of the declaration is not mandatory.

Example:

enum enums
 {
     A, B, C, D     //semicolon at the end of this statement is not mandatory
 }

Enum can have an abstract method declared in body provided each enum constants declared in the class must implement it.

enum enums
 {
     ONE
     {
         @Override
         void abstractMethod()
         {
             //Abstract Method Implemented
         }
     },
  
     TWO
     {
         @Override
         void abstractMethod()
         {
             //Abstract Method Implemented
         }
     },
  
     THREE
     {
         @Override
         void abstractMethod()
         {
             //Abstract Method Implemented
         }
     };
  
     abstract void abstractMethod();
 }

Leave a Reply