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

Saturday, 16 May 2015

Static And Dynamic Binding In Java

Association of method definition to the method call is known as binding. There are two types of binding: Static binding and dynamic binding. Lets discuss them one by one.

Static Binding or Early Binding

The binding which can be resolved at compile time by compiler is known as static or early binding. All the static, private and final methods have always been bonded at compile-time . Why binding of Static, final and private methods is always a static binding? You would understand it better after reading dynamic binding. Still let me explain this – Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static.

Static binding example :

class Boy{
   public void walk(){
      System.out.println("Boy walks");
   }
   public static void main( String args[]) {
      Boy boy = new Boy();
      boy.walk();
   }
}

Dynamic Binding or Late Binding

When compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding. Overriding is a perfect example of dynamic binding as in overriding both parent and child classes have same method. Thus while calling the overridden method, the compiler gets confused between parent and child class method(since both the methods have same name).

Dynamic binding example :

Here Human is a super class and Boy is a child class since Boy extends Human. Both these classes have a same method void walk(). Since we have assigned the parent class reference to the child class object, during call of walk() method the compiler would not be able to decide which walk() method to call. It will be confused between the walk() method of Human class and walk() method of Boy class. Such kind of bindings are known as dynamic binding as compiler figures out the object type in runtime.

class Human{
   public void walk()
   {
       System.out.println("Human walks");
   }
}
class Boy extends Human{
   public void walk(){
       System.out.println("Boy walks");
   }
   public static void main( String args[]) {
       //Reference is of parent class
       Human myobj = new Boy();
       myobj.walk();
   }
}

Output:

Boy walks

Static Binding vs Dynamic Binding

Lets discuss the difference between static and dynamic binding in Java.
  • Static binding happens at compile-time while dynamic binding happens at runtime.
  • Binding of private, static and final methods always happen at compile time since these methods cannot be overridden. Binding of overridden methods happen at runtime.
  • Java uses static binding for overloaded methods and dynamic binding for overridden methods.