Thursday, June 13, 2013

Interface in java


 An interface is a group or collection of abstract methods or incomplete methods. A class implements methods should override declared method in interface. All methods should be public in interface because of access of method in implemented class.
 An interface is implicitly abstract so we don't need to use abstract keyword. And all method of interface also by default abstract and incomplete.

Points for interface declaration and use:

1:- Method of interface should not static and final, You can't create static methods in interfaces. All methods are instance methods.
2:- All variables in interface are by default public static final. So we don't need to use it. if we use it , it will be redundant.
3:- Interface can not be instantiated.
4:- Interface have .java extension.


Example:-

public abstract interface TestInterface{   // Interfaces are always abstract

public static final String EX_CONSTANT = "ABC";
public static final int EX_INT_CONSTANT = 5;
public static final double EX_DOUBLE = 5.0;
public static final Integer EX_INTEGER = 10;

public void testMethod(); // Interface methods are always public
    abstract void anotherTestMethod(); // Also redundant

}

Difference between Interface and Class :-

1:- we can not create object of interface.
2:- it don't have constructor.
3:- Method of interface are abstract.
4:- It have incomplete methods.
5:- Method must be public.
6:- All variable is by default public static final.
7:- An interface can extends mulple interface.
8:- An interface not extended by class , it is implemented.

Example:-

/* File name : Dog.java */
interface Dog {

   public void bark();
   public void eat();
}


Now implementing interface in Behaviour.class

/* File name : Behaviour.java */
public class Behaviour implements Dog{

   public void eat(){
      System.out.println("eat");
   }

   public void bark(){
      System.out.println("bark");
   }

 

   public static void main(String args[]){
      Behaviour obj = new Behaviour();
      obj.eat();
      obj.bark();
   }
}