Friday, September 2, 2016

Enums in Brief

public enum Month {
JANUARY(1), FEBRUARY(2), MARCH(3), APRIL(4), MAY(5), JUNE(6), JULY(7), AUGUST(8), SEPTEMBER(9),OCTOBER(10),NOVEMBER(11),DECEMBER(12);

    private int monthIndex;
     private Month(int monthIndex) {
        this.monthIndex = monthIndex;
    }
     public int getMonthIndex() {
        return this.monthIndex;
    }
}
Using this approach, you don’t have to worry about serialization problems as enums (are serializable by default) handles it for you. This approach is more cleaner and is considered to be the best way to implement a singleton.
public enum SessionFactory {
     SESSION_FACTORY;
     public void doSomething() {
        System.out.println("I am doing something");
    }
}
Before Java 5: a traditional enumerated type identifying weeks:
use these constants within the code for comparisons and all like if(weekDay == Weekday.SUNDAY){//do something} where weekDay is an integer var.
However weekDay may contain any other integers also like 8 or 9, as there is no restriction set by the compiler.
an enum in java:
Weekend is actually a class and SATURDAY and SUNDAY are instances of the class Weekend. Behind the scenes, the compiler converts enum Weekend {---------} into a class like 
Compiler calls the default construction to create instance as above so

Enhance an enum
assign a different behavior to each constant by introducing an abstract method into the enum and overriding this method in an anonymous subclass of the constant.

Weekend.SATURDAY.someMethod()
Enum constants are implicitly static and final and you can not change there value once created.
Currency.PENNY = Currency.DIME;  X
You can specify values of enum constants at the creation time as shown in below 
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;
        private Currency(int value) {
                this.value = value;
        }
//to get the value associated with each coin you can define a 
public int getValue(){
return value
}
};   

constants defined inside Enum in Java are final you can safely compare them using "==" equality operator 
Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
  System.out.println("enum in java can be compared using ==");
}
Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum. These classes are high performance implementation of Map and Set interface in Java 

No comments:

Post a Comment