Inheritance is one of the key features of OOP that allows us to create a new class from an existing class.
The new class that is created is known as subclass (child or derived class) and the existing class from where the child class is derived is known as superclass (parent or base class).
The extends keyword is used to perform inheritance in Java. For example,
When the child class extends from more than one superclass, it is known as multiple inheritance. However, Java does not support multiple inheritance.
To achieve multiple inheritance in Java, we must use the interface.
Example: Multiple Inheritance in Java
interface Backend {
// abstract class
public void connectServer();
}
class Frontend {
public void responsive(String str) {
System.out.println(str + " can also be used as frontend.");
}
}
// Language extends Frontend class
// Language implements Backend interface
class Language extends Frontend implements Backend {
String language = "Java";
// implement method of interface
public void connectServer() {
System.out.println(language + " can be used as backend language.");
}
public static void main(String[] args) {
// create object of Language class
Language java = new Language();
java.connectServer();
// call the inherited method of Frontend class
java.responsive(java.language);
}
}
Output
Java can be used as backend language. Java can also be used as frontend.
In the above example, we have created an interface named Backend and a class named Frontend. The class Language extends the Frontend class and implements the Backend interface.
Here, the Language class is inheriting the property of both Backend and Frontend. Hence, we can say it is an example of multiple inheritance.:
Advantages of Interface in Java
Now that we know what interfaces are, let's learn about why interfaces are used in Java.
- Similar to abstract classes, interfaces help us to achieve abstraction in Java.
Here, we know getArea() calculates the area of polygons but the way area is calculated is different for different polygons. Hence, the implementation of getArea() is independent of one another. - Interfaces provide specifications that a class (which implements it) must follow.
In our previous example, we have used getArea() as a specification inside the interface Polygon. This is like setting a rule that we should be able to get the area of every polygon.
Now any class that implements the Polygon interface must provide an implementation for the getArea() method. - Interfaces are also used to achieve multiple inheritance in Java. For example,
interface Line { … } interface Polygon { … } class Rectangle implements Line, Polygon { … }
Here, the class Rectangle is implementing two different interfaces. This is how we achieve multiple inheritance in Java.