Interface in Java

Before learning interface in java, you must know about abstraction. So lets learn about what is abstraction.

Abstraction in Java

  • Abstraction is the process of hiding the complexity and
    showing the functionality. Showing the essential data and hiding the non
    essential data. 
  • We can understand this by taking a real world example. We have fan in house, we are just provided with a switch (functionality) to turn on and off the fan, we are not aware of how the fan actually works (complexity). This is a perfect example of abstraction in java.

Interface in Java

  • Interface is used to achieve fully implementation of
  • Interface contains only abstract methods. Abstract method is
    a method without body. 
  • In an interface, by default all the data members are public,
    static and final while all the methods are public and abstract. 
  • Interface is used to achieve multiple inheritance in java.
    We will discuss about it in this tutorial. 
  • Same as like abstract class we can’t create object of an interface.
We can define an interface in java using “interface”
keyword. A simple example is given below.

You must keep in mind that a class implements another
interface and an interface extends another interface.

Interface in Java

A class implements another interface

interface in java
In above example we have created an interface and a class.
The class is implementing the interface. You can see that I have written public
keyword while defining the show() method in class MyClass. This is because if
we do not write public then compiler we take “default” as a default access specifier
and will show an error. For overriding a method the child must be equal or stronger
than the parent. Here parent is MyInterface and inside it the access specifier of
show() method is public. So to make the method of child class MyClass equal to the Parent
MyInterface, we have written “public” keyword while defining the show() method.

An interface extends another interface

Interface 1
Interface 2

Multiple Inheritance in Java

Multiple inheritance can’t be achieved using class only but
it can be achieved easily using interface. It can be done in following way.

Multiple Inheritance in Java
In above example you can see that MyClass is implementing
two interfaces at a time, so this is an example of multiple inheritance in
This was all about interface in java. In the next tutorial I
will discuss about the difference between abstract class and interface. If you
find anything incorrect or have doubt regarding above tutorial then please
mention it by commenting below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.