Java Interface2 min read

An Interface in Java is the same as class, like any other class, an interface can have methods and Variables. But unlike a class, the method in it is an abstract method (only method signature, contain no body)and also by default, the declared variables in an interface are public, static & final.

Uses of Interfaces:

  • It is used to achieve abstraction.
  • As we have learned that Java does not support multiple inheritance but through the interface, we can achieve multiple inheritance.
  • It is also used to achieve loose coupling.

Note: Abstraction cannot be used to create objects. Hence it cannot contain a constructor.

Declaring an Interface in Java:

The keyword ‘interface‘ is used to declare an interface.
Syntax of Interface in Java:

Syntax of interface in Java with an example:

Implementation of Interface in Java:

To implement an interface in a class, we use the keyword ‘implements’ The following example shows the use of implements. Below class, Puppy implements the interface Dog.

Output of Interfaces in Java:

Multiple Interfaces and inheritance in Java:

We know class in java allows only a single extends but with the use of interfaces, we can implement more than one parent interface.

Java Interface
Java Interface

In the diagram above,
  The class extends a class
  The interface extends interface
  class implements interface

Example of Multiple Interface in Java:


Access Modifier.