Saturday, 30 May 2015

Java Enum Type Examples

Enums in java are mainly used for grouping similar kind of constants as a one unit. constants means static and final. Enums are introduced in JDK 1.5 onward. Before that similar kind of constants are grouped by declaring them as static and final in one class. 

Points to remember for Java Enum :
  • enum improves type safety
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class
  • Every constant of enum is public, static and final by default. As every constant is static, they can be 
  • accessed directly using enum name.
Every constant of enum is public, static and final by default. As every constant is static, 
they can be accessed directly using enum name.

Simple example of java enum :

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

Enums in java are declared with enum keyword and constants in enums must be valid java identifier. It is good practice to declare constants with UPPERCASE letters.

enum Days
{
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, 

SATURDAY, SUNDAY;
}

Duplicate enum constants are not allowed.

enum Directions
{
    NORTH, NORTH, SOUTH, EAST, WEST;  //Compile Time Error : Duplicate Constants
}

Initializing specific values to the enum constants The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific value to the enum constants by defining  fields and constructors. As specified earlier, Enum  can have fields, constructors and methods.

Example of specifying initial value to the enum constants

class EnumExample4{  
enum Season{   
WINTER(5), SPRING(10), SUMMER(15), FALL(20);   
private int value;  
private Season(int value){  
this.value=value;  
}
}  
public static void main(String args[]){  
for (Season s : Season.values())  
System.out.println(s+" "+s.value);  

}}  
      
Output: WINTER 5
       SPRING 10
       SUMMER 15
       FALL 20

Enums can have any number of fields. methods and constructors and Each constant will have their own copy of fields and methods.

enum enums
{
    A, B, C;
    int i;  //enums can have fields
    private enums()
    {
        //enums can have Constructor
    }
    void methodOfEnum()
    {
        //enums can have methods
    }
}
public class EnumsExample
{
    public static void main(String[] args)
    {
        enums en = enums.A;
        System.out.println(en.i);   //Constant A has field i
        en.methodOfEnum();         //Constant A has methodOfEnum()
        enums en1 = enums.B;
        System.out.println(en1.i);   //Constant B has field i
        en1.methodOfEnum();         //Constant B has methodOfEnum()
        enums en2 = enums.C;
        System.out.println(en2.i);   //Constant C has field i
        en2.methodOfEnum();          //Constant C has methodOfEnum()
    }
}

If enum has only constants, then semicolon (;) at the end of constant declaration is not mandatory. But, if enum has other members, then semicolon is mandatory.

enum enums
{
    A, B, C, D     //semicolon at the end of this statement is not mandatory
}
enum enums
{
    A, B, C;  //semocolon at the end of this statement is mandatory, because it has other embers
    int i;    //enums has a field
    void methodOfEnum()
    {
        //enums has a method
    }
}

Every enum in java extends java.lang.Enum class. Enum class is an abstract class in java.lang 
package. As every enum extends Enum class, it should not extend any other class. Because, Multiple inheritance is not allowed in java. But enums can implement any number of nterfaces.

interface AnyInterface
{
    abstract void methodOfInterface();
}
enum enums implements AnyInterface
{
    A, B, C;
    @Override
    public void methodOfInterface()
    {
        //MethodOfInterface is implemented
    }
}

Enums can be declared inside a class. If declared inside a class, they are static by default and can be accessed directly by Class name.

class ClassContainingEnum
{
    enum enums
    {
        A, B, C
    }
}
public class MainClass
{
    public static void main(String[] args)
    {
        System.out.println(ClassContainingEnum.enums.A);  //Accessing enums directly using class name
    }
}

Enum constants can override generalized method defined in the enum body.

enum enums
{
    FIRST
    {
        @Override
        void commonMethod()
        {
            System.out.println("Common method Overridden in FIRST");
        }
    },
    SECOND
    {
        @Override
        void commonMethod()
        {
            System.out.println("Common method Overridden in SECOND");
        }
    };
    void commonMethod()
    {
        System.out.println("Generalized method, Common to all constants");
    }
}
public class EnumsExample
{
    public static void main(String[] args)
    {
        enums.FIRST.commonMethod();     //Output : Common method Overridden in FIRST
        enums.SECOND.commonMethod();   //Output :Common method Overridden in SECOND
    }
}

Enum can have abstract method declared in it’s body provided each enum constants must implement it.

enum enums
{
    FIRST
    {
        @Override
        void abstractMethod()
        {
            //Abstract Method Implemented
        }
    },
    SECOND
    {
        @Override
        void abstractMethod()
        {
            //Abstract Method Implemented
        }
    },
    THIRD
    {
        @Override
        void abstractMethod()
        {
            //Abstract Method Implemented
        }
    };
    abstract void abstractMethod();
}

Enum Constants can have their own fields and method defined in their body, but these fields and methods are visible only within the constant body.

enum enums
{
    FIRST
    {
        int j = 10;   // Field of FIRST
        void methodOfFirst()
        {
            System.out.println(j);  //Field j can be used within the constant body
        }
        @Override
        void abstractMethod()
        {
            methodOfFirst();     //methodOfFirst() can be used within the constant body
        }
    },
    SECOND
    {
        int k = 20;   //Field of SECOND 
 void methodOfSecond()
        {
            System.out.println(k);  //Field k can be used within the constant body
        }
        @Override
        void abstractMethod()
        {
            methodOfSecond();     //methodOfSecond() can be used within the constant body
        }
    };
    int i;   //this field is available in all constants
    abstract void abstractMethod();  //this method is available in all constants
}

public class EnumsExample {
 public static void main(String[] args){
System.out.println(enums.FIRST.j); //Compile time error : Field j is not visible here
enums.FIRST.methodOfFirst();  //Compile time error : methodOfFirst() is not visible here
enums.FIRST.abstractMethod();
System.out.println(enums.SECOND.k); //Compile time error : Field k is not visible here
 enums.SECOND.methodOfSecond();      //Compile time error : methodOfSecond() is not visible here
 enums.SECOND.abstractMethod();
    }
}

We can apply enum on switch statement as in the given example:

class EnumExample5{  
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
THURSDAY, FRIDAY, SATURDAY}  
public static void main(String args[]){  
Day day=Day.MONDAY;  
switch(day){  
case SUNDAY:   
 System.out.println("sunday");  
 break;  
case MONDAY:   
 System.out.println("monday");  
 break;  
default:  
System.out.println("other day");  
}  
}}  

Output: monday

No comments:

Post a Comment