June 12, 2011

enum in Java (Enumerated data types)

Enumerated data types can be created in Java with the enum keyword. Variable declared of the enum type can then only hold values listed in the definition of the enum type.

enums can be declared within a class as a class member or outside a class. When declared inside a class as a member, access modifiers can be applied to the enum and the same rules of access modifiers as for other members apply to an enum as well. An enum declaration also needs the enclosing class-name when accessing it outside the class.

An enum however cannot be declared within a method.

Just like a class, enums can have constructors, instance variables and methods.
An enum constructor, unlike a class constructor, cannot be directly invoked. It can only be invoked from within the enum from the listed enumerated values.


package info.icontraining.core;

enum Gender { MALE, FEMALE };

public class EnumExample {
 
   enum Color { 
      
      SAFFRON("top"), WHITE("middle"), GREEN("bottom");

      private String position;

      Color(String position) {
         this.position = position;
      }
 
      public String getPosition() {
         return this.position;
      }
   };
  
   Color color;   
   Gender gender;

   public static void main(String[] args) {
      EnumExample e = new EnumExample();
  
      e.gender = Gender.MALE;
      e.color = EnumExample.Color.SAFFRON;
  
      System.out.println(e.color.getPosition());
   }
}

1 comment:

  1. fantastic post man. you have covered the topic quite well and Indeed Enum are more versatile than one can think of , see the below post 10 examples of enum in java to know what else can you do with enum in java.

    Thanks
    Javin

    ReplyDelete