Interface in Java

Table of Contents

Interface in Java

By now, we have entered into the concept of Data Abstraction in Java. Actually Data Abstraction is providing only the outline of a class or method rather than describing the entire of its code.

Now,Data Abstraction is implemented using two keywords which are:

  • Interface
  • Abstract

In this tutorial, we will be dealing with the concept of implementing the usage of Interface.

Let us see, how to use Interface with a small example.

interface simple
{  
  void display();  
}  
class Sample implements simple
{  
  public void display()
  {
    System.out.println("Implemented successfully");
  }  
public static void main(String args[])
{  
  Sample obj = new Sample();  
  obj.display();  
 }  
}  

In the above example, you can notice that the pattern of implementing an interface is similar to the concept of Inheritance, with the only provided difference is the keyword used. Here we have used the keyword implements while for Inheritance, we have used extends keyword.

Now, here is a special feature because of which Interface is used. It eradicates the problem of not supporting multiple inheritances in Java.

But,How Interface does it?

So, previously the problem was ambiguity, which restricted it’s usage, as the Compile Time error is preferred over Run time error in JVM. Now, Interface has a solution for it as it’s implementation is provided by the Implementation Class of JAVA.

Now ,What is Implementation Class?

An implementation class is a class that may have attributes, associations, operations, and methods. An implementation class defines the physical implementation of objects of a class.

Now, let’s see an example of the Implementation Of Multiple Inheritance in Java through it.

interface Rough
{  
 void display();  
}  
interface Tough
{  
 void show();  
}   
class Sample implements Rough, Tough
{  
  public void display()
  {
   System.out.println("Multiple");
  } 
  public void show()
  {
   System.out.println("Inheritance");
  }
  public static void main(String args[])
  {  
  Sample obj = new Sample();  
  obj.display();  
  obj.show();
 }  
}

Leave a Reply