Interface

 An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

 

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. A class that implements an interface must implement all the methods declared in the interface.


Syntax:

interface <interface_name>{  

      

    // declare constant fields  

    // declare methods that abstract   

    // by default.  

}  


Internal addition by the compiler

 

The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.

 

In other words, Interface fields are public, static and final by default, and the methods are public and abstract.


The relationship between classes and interfaces

 

As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface.



Multiple inheritance in Java by interface

 

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.


Interface inheritance

 

A class implements an interface, but one interface extends another interface.


Java 8 Default Method in Interface

 

Since Java 8, we can have method body in interface. But we need to make it default method.


Java 8 Static Method in Interface

 

Since Java 8, we can have static method in interface.


Nested Interface in Java

 

Note: An interface can have another interface which is known as a nested interface.

Post a Comment

0 Comments