Coders Packet

Interface in Java

By Aryan Pradhan

In this tutorial we will learn about the concept of Interface in java. We learn about interface through a simple code.

What is Interface?

The interface. is a blueprint of classes. An interface is a method to achieve 100% abstraction and multiple inheritance. An interface can have methods and variables only. An interface can have only abstract methods, not the body of the method. An interface specifies what a class must do and not what to do. Since java does not support multiple inheritance we can achieve it through the interface.The interface represents the IS-A relationship.

Syntax:

  1. interface  interface_name{  
  2.       
  3.     // declare constant fields  
  4.     // declare methods that abstract   
  5.     // by default.  
  6. }  

Use of Interface

1. By using the interface we can achieve multiple inheritance.

2. Interface is used to achieve 100% abstraction.

3. It can also be used to achieve loose coupling.

 

Code

interface shape{


void draw();


}


class rectangle implements shape{


public void draw(){


System.out.println("Drawing Rectangle");


}
}
class square implements shape{


public void draw(){


System.out.println("Drawing Square");


}
}


class sample{


public static void main(String args []){


shape s=new square();


s.draw();
}
}

 

Output:

Drawing Square

Download Complete Code

Comments

No comments yet