Friday, 30 May 2014

Java Enum Tutorial

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Example:

public enum Month {
    JAN, FEB, MAR, APR,
    MAY, JUN, JUL,AUG,SEP,OCT,NOV,DEC
}

 here points to remeber:
 1.  enum is a keyword.
 2.  members are constants so all should be in capital.
 3. enum constants are implicitly static final.
 4. enum are introduced in java from 1.5

We can declare java constants in two ways.
 1. using enum
 2. public static final {type}

 advantages of enum over public static final.
Let me explain with a small example.
//WEEK CONSTANTS DECLARED USING final.

  public  class Day {
 public static final  MON = 1;
 public static final  TUE = 2;
 public static final  WED = 3;
 public static final  THU = 4;
 public static final   FRI =  5;
 public static final   SAT = 6;
 public static final   SUN= 7;
}
public calss WeekDay {
int weekDay ;
   weekDay = 20;
//assign 20 to weekDay.

}
 Though this can serve our purpose it has some serious limitations:
 1.No Type Safe:
     you can assign any value to weekDay. example: weekDay = 20;
      though there is no week to represent that value.
2. No namespace:

to access the WeekDay constant we need to prefix class name e.g. WeekDay.MON instead of just using MON though this can also be achieved by using static import in JDK 1.5

3.Printing:  printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print MON it will print "1" instead of "MON"

Best solution for all these limitations is enum in java.
i will explain the same example using enum.
public enum Day {
//constants for the week.
MON,TUE,WED,THU,FRI,SAT,SUN
}

public class EnumExmple {
    public static void main(String[] args) {
        Day weekDay;
  // weekDay = 20; it gives error, you can't do that here.
          weekDay = Day.MON;
//here it provides name space as well as type safe.
//type safe:       only Day constants can assign to weekDay
//name space:   to access MON only way is Day.MON.
  System.out.print(weekDay.ordinal());//prints the number
          System.out.print(weekDay);// prints MON

    }

}

Constructor with enum:

public enum Day {
MON(1),TUE(2),WED(3),THU(4),FRI(5),SAT(6),SUN(7);
int value;
  private Day(int value){
    this.value = value;
}
  public int getValue(){
      return value;
  }
}

we can write constructor in enum type as shown above.
access specifier of the constructor must be private other wise you will get compiler error. to retrieve value from the enum write a method like getValue();

Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Day.MON = Day.SUN;
The final field EnumExamples.Day.SUN cannot be re assigned.
NOTE1: you cannot create  object for the Enum type because Enum cunstructor is private and Enum constatns created inside Enums. 

NOTE2: Instance of Enum in Java is created when any Enum constants are first called or referenced in code.
enum can be used in switch :
 like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:  

        
           weekDay = Day.SUN;
            switch (weekDay) {
                    case SUN:
                            System.out.println("Sunday");
                            break;
                    case MON:
                            System.out.println("Monday");
                            break;
                    case TUE:
                            System.out.println("Tuesday");
                            break;
                    case WED:
                            System.out.println("Wednesday");
            }

    }

Enum constants can be compared:

  if(weekDay == Day.SUN){
}
loop with enum:
for(Day day: Day.values()){
                System.out.println(day); //prints enum constant as it is
                System.out.println(day.value);// prints its integer value.
            } 
 Enum with abstaract method:

public enum Day {

    MON(1, "Monday") {
        @Override
        public String getName() {
            return weekName;
        }
    },
    TUE(2,"Tuesday") {
        @Override
        public String getName() {
            return weekName;
        }
    },WED(2,"Wednesday") {
        @Override
        public String getName() {
            return weekName;
        }
    } ,THU(2,"Thursday") {
        @Override
        public String getName() {
            return weekName;
        }
    }, FRI(2,"Friday") {
        @Override
        public String getName() {
            return weekName;
        }
    }, SAT(2,"Saturday") {
        @Override
        public String getName() {
            return weekName;
        }
    },SUN(2,"Sunday") {
        @Override
        public String getName() {
            return weekName;
        }
    };
    int value;
    String weekName;

    private Day(int value, String name) {
        this.value = value;
        weekName = name;
    }

    public int getValue() {
        return value;
    }
//abstract method.
    public abstract String getName();
}

In the above example Enum constructor have two parameters

 1. int 2. String

abstract method has created anonymously as show here:
  SUN(2,"Tuesday") {
        @Override
        public String getName() {
            return weekName;
        }
    };

Enum with interface: Enum can implement interface like any class in java, By default enum implements Serialiizable  and Runnable interfaces.

public enum Day implements Runnable{
  SUN(1), MON(5), TUE(10), SAT(25);
  private int value;
  ............
        
  @Override
  public void run() {
  System.out.println("implements interface");
                
   }
}

 

2 comments: