Interface in Java

Hello friends how are you, today in this blog i will teach you what is interface, how and why interface is used , how interface works and many programs using interface  in a very simple way. 

Let's start

1.interface is an important element in java which is called reference type.
2.It is blueprint of class.
3.It is a collection of abstract method/function.
4.It is declared with interface keyword.
5.We can not create instance(object) of an interface.
6.We can not define function inside interface only can be declared,so it is the responsibility of derived class to implement the method/function of interface.
7.A class is extended by a class but an interface is implemented by a class.

Example


interface Geometry
{
  void rectangle_area(int height,int width);
  void square_area(int side);  
  void circle_area(float radius);          
}
/*implementing interface*/
class Easy implements Geometry
{
 /*implementing method of interface*/
 public void rectangle_area(int height,int width)
 {
  int ar=height*width;
  System.out.println("Area of rectangle="+ar);
 }
  /*implementing method of interface*/
 public void square_area(int side)
 {
  int ar=side*side;
  System.out.println("Area of square="+ar);
 }
  /*implementing method of interface*/
 public void circle_area(float radius)
 {
  float ar=3.14f*radius*radius;
  System.out.println("Area of circle="+ar);
 }
 public static void main(String[] args)
 {
   /*creating instance of derived class*/
   Easy obj=new Easy();
   obj.rectangle_area(12, 13);
   obj.square_area(12);
   obj.circle_area(2.2f);
 }
}
/*
### Output ###
Area of rectangle=156
Area of square=144
Area of circle=15.197601
*/
Here in the above program Geometry is an interface that contains three methods which will be implemented by child class. Easy class is a class that implements the interface so it is the responsibility of class Easy to implement methods of interface, That's why all the methods of interface is defined in the class Easy.

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. 

Thanks.😊

Post a Comment

0 Comments