In this article, we will learn how to create an interface in java. So, let’s start – Does Java support multiple inheritances? No, Java does not support multiple inheritances but there is always an alternative approach for everything that Java does not support. For multiple inheritances, it is an approach called ‘Interface‘.
Create interface in java
Now we will discuss the topic in detail, first of all, we will learn what is in A means of achieving full abstraction and multiple inheritances. contains constant values and method declaration. The main difference between class and the interface is that the interface only contains the method declaration neither the method definition nor instance variable.
An interface is declared by using the interface keyword. It provides total abstraction; which means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Following fig. shows the simplest example of multiple inheritances:
Here class Vehicle will display the mode of moving of class Boat or Car. But the compiler will get confused about which class move() to call. This is the reason that java does not support multiple inheritances. To overcome this the above can be written programmatically as follow:
Example:
Interface Mode{
protected void move();
}
class Car implements Mode{
move(){
System.out.println(“On road”);
}
}
class Boat implements Mode{
move(){
System.out.println(“On water”);
}
}class DisplayMove{
public static void main(String args[]){
Car c=new Car();
Boat b=new Boat();
c.move();
b.move();
}
}
Thanks for reading, you can share this article with your friends and Learn the Interface in Java Programming Language. A class that implements an interface must implement all the methods declared in the interface. The methods must have the same signature (name + parameters) as declared in the interface. The class does not need to implement (declare) the variables of an interface. Only the methods.