Interface

Interface are similar to the class in java. Interface has only empty methods or final data member. All methods declared inside interface treated as abstract internally. So programmer no need to mention it explicitly by using abstract keyword.



Syntax :


	 interface <interface_name> 
{
// method and constant;
}

Syntax :


	 interface one 
{
void show();
void clear();
void draw();
}

Above program is a example of interface. Interface is implemented in class where all interface's method will be defined.

Note ! Compiler automatically put public and abstract keyword with every method declared in interface.

So we can say compiler will transform above interface into

Program :


 // Compiler transform above interface into this 
interface one
{ public abstract void show();
public abstract void clear();
public abstract void draw();
}


In interface only constant can be declared. Compiler automatically add public and static with every constant declared in interface.


Program :


	 interface one 
{
final int DIM=4;
final float d=1.23f;
void show();
void clear();
void draw();
}

Compiler perform internal transformation of above interface by adding public, static keyword with each constant and public, abstract with each method declared in interface.




	 // This is done by compiler internally.
interface one
{
public static final int DIM=4;
public static final float d=1.23f;
public abstract void show();
public abstract void clear();
public abstract void draw();
}

interface in java support multiple inheritance. Interface has only empty bodies of methods.



Implementation of Interface

Interface can be implemented in class. Class has to provide definition of all method of interface otherwise that class become abstract class.


Program : To implement interface one


  interface one
{
final int DIM=4;
final float d=1.23f;
void show();
void clear();
void draw();
}
class two implements one // interface method must be implemented with public keyword.
{
public void show(){System.out.println("Show method");}
public void clear(){System.out.println("Show method");}
public void draw(){System.out.println("Show method");}
}