Java Interface

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.

Use 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:

The keyword ‘interface’ is used to declare an interface.
Syntax:

Syntax of interface with an example:

Implement Interface:

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:


Multiple Interfaces and inheritance:

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

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

Example of Multiple Interface:

Output: