Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Multiple Inheritance in Java?
2.1.
Example of Multiple Inheritance in Java
2.2.
Java
3.
Why is Multiple Inheritance Not Supported in Java?
4.
Different Methods to Implement Multiple Inheritance in Java
4.1.
Java
4.2.
Java
5.
An Alternative to Multiple Inheritance in Java
5.1.
Java
6.
Multiple Inheritance in Java Interfaces
7.
Frequently Asked Questions
7.1.
What is multiple inheritance in Java?
7.2.
What is a real time example of multiple inheritance?
7.3.
How multiple inheritance is achieved in Java?
7.4.
Why multiple inheritance is not possible in Java?
7.5.
What is the limitation of multiple inheritance in Java?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Multiple Inheritance in Java

Author Akash
2 upvotes
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Multiple Inheritance is a powerful object-oriented programming concept where a class can inherit attributes and behaviors from more than one superclass. This allows for greater flexibility in designing and structuring classes, enabling the creation of complex and modular code structures.

multiple inheritance in java

In this article, we will discuss Multiple Inheritance in Java, which will include the reason why multiple inheritance in java is not supported and how to deal with this problem.

Let's first discuss a little bit about inheritance and the types of inheritance.

What is Multiple Inheritance in Java?

Java doesn't allow a class to inherit from more than one class directly, preventing multiple inheritance to avoid complexity and ambiguity. However, a Java class can still gain functionality from multiple sources by implementing multiple interfaces, effectively bypassing this restriction and promoting a cleaner, more organized approach to inheriting features and behaviors.

In our example of Inheritance above, we showed that a kid inherits attributes from only their mother, but that doesn't happen in reality. A child inherits qualities from both parents, as shown below.

multiple inheritance example


Considering the parents as the base classes and the kid as the derived class, we can see that a single derived class inherits attributes from multiple base classes. This is known as multiple inheritance in Java.

multiple inheritance example

Also see, Swap Function in Java

Example of Multiple Inheritance in Java

Let's consider, we are building a multimedia application. It involves different types of media objects(images, videos, etc.). We want these media objects to have both display and play features. We also want to keep their implementations separate. Let us try to implement these:

  • Java

Java

// Interface for displaying 
interface DisplayInterface {
void display();
}

// Interface for playing
interface PlayInterface {
void play();
}

// Class that implements DisplayInterface
class Image implements DisplayInterface {
@Override
public void display() {
System.out.println("This function is for displaying the image");
}
}

// Class that implements DisplayInterface and PlayInterface
class Video implements DisplayInterface, PlayInterface {
@Override
public void display() {
System.out.println("This function is for displaying the video");
}

@Override
public void play() {
System.out.println("This function is for playing the video");
}
}

class Main {
public static void main(String[] args) {
Image img = new Image();
Video vid = new Video();

img.display();
vid.display();
vid.play();
}
}

Output:

output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why is Multiple Inheritance Not Supported in Java?

The main reason for not allowing multiple inheritances in Java is the ambiguity around the diamond problem. 

Consider a class NinjaA that contains a Coding() method. Classes NinjaB and NinjaC were derived from class NinjaA and each had a Coding() implementation. Class NinjaD is now derived from classes NinjaB and NinjaC using multiple inheritances. If we refer to simply Coding(), the compiler would not be able to determine which Coding() it should call.

Because of the inheritance scenario's structure, which resembles a four-edged diamond, this problem is also known as the "Diamond Problem."

 

diamond problem in multiple inheritance

The second and more convincing justification is that having multiple inheritances complicates the design and causes issues with casting, constructor chaining, etc. You can refer to the diagram below to understand it better.

diamond problem in multiple inheritance

Different Methods to Implement Multiple Inheritance in Java

As we already know, Multiple Inheritance is not supported in Java because of the ambiguity caused by methods or attributes with the same name. However, we can solve this problem by using interfaces instead of classes.

An Interface is the blueprint of a class that implements abstraction by using abstract methods. Declaring interfaces is easy and can be done by simply using the ‘interface’ keyword.

 

Now you may be wondering how using an interface solves the problem we were facing before. 

To understand the reason, let us consider our previous example, but we’ll use an interface instead of a class this time. 

  • Java

Java

//First interface
interface A {
default void text() {
System.out.println("Hello");
}
}

//Second interface
interface B {
default void text() {
System.out.println("What's your name?");
}
}

class C implements A, B {

//Default method in interface is overriden
public void text() {

//text() method from first interface is called
A.super.text();

//text() method from second interface is called
B.super.text();
}
}

class Main {
public static void main(String args[]) {
C obj = new C();
obj.text();
}
}

Output:

Hello
What’s your name?

 

Here, the text( ) methods from both the interfaces A and B are called separately, thereby eliminating the confusion about which class’s method to call. 

Another method in which we can use interfaces for Multiple Inheritance is by using abstract methods. This method is shown below. 

  • Java

Java

// Interface 1
interface A {

// Abstract method
public abstract void text1();
}

// Interface 2
interface B {

// Abstract method
public abstract void text2();
}

// Interface is implemented
class C implements A, B {

// Abstract methods are overridden
public void text1() {
System.out.println("Hello");
}

public void text2() {
System.out.println("What's your name?");
}
}

class Main {
public static void main(String[] args) {

//Create a C object
C obj = new C();
obj.text1();
obj.text2();
}
}

Output:

Hello
What’s your name?

 

Here, two abstract methods text1() and text2() are declared in the interfaces, which are overridden in the derived class C. 

If you've made it this far, we're confident that you have a firm grasp on Multiple Inheritance in Java. Before we wrap up this blog, let's look at some frequently asked Java questions.

An Alternative to Multiple Inheritance in Java

When a class can derive from numerous parent classes, this is known as multiple inheritances, and it can complicate and create disputes within the inheritance hierarchy. Java does not provide multiple class inheritance, unlike other programming languages like C++.
Java promotes interfaces, which specify a set of methods a class implementing the interface must follow. Classes may define and execute behavior using interfaces without defining the specifics of the implementation. A class can inherit numerous contracts and uses polymorphism by implementing interfaces.

  • Java

Java

interface InterfaceX {
void action1();
}

interface InterfaceY {
void action2();
}

class MyClass implements InterfaceX, InterfaceY {
public void action1() {
System.out.println("Executing action1 command...");
}

public void action2() {
System.out.println("Executing action2 command...");
}
}

public class Main {
public static void main(String[] args) {

//Create an instance of MyClass
MyClass myObj = new MyClass();

//Call the action1 method
myObj.action1();

//Call the action2 method
myObj.action2();
}
}

Output:

Executing action1 command...
Executing action2 command...

Multiple Inheritance in Java Interfaces


A class can inherit features and actions from multiple interfaces in Java programming. Since Java doesn't offer multiple inheritances options among classes, like some programming languages, a single class is limited to extending another class. On the other hand, it allows multiple inheritance through interfaces.
A variety of inheritance through interface promotes a more adaptive and modular approach to design. It promotes code reuse and polymorphism by enabling a class to be a component of many object hierarchies.

In our example of Inheritance below, two interfaces and three classes implement those interfaces. The name of the interfaces are 'playing' and 'studying,' and the classes are 'Teachers,' 'Parents,' and 'Student.' The interface 'playing' and 'studying' consists of a single method, 'play()' and 'study().' When the 'Teachers' class implements the playing interface, it indicates implementing the 'play()' method. When a Teachers() object is created, the 'play()' method is called, printing the corresponding statements. 

Frequently Asked Questions

What is multiple inheritance in Java?

In Java, multiple inheritance means inheriting from more than one parent class, which isn't directly supported by classes. Instead, Java uses interfaces for a form of multiple inheritance called "interface-based multiple inheritance." This allows classes to implement multiple interfaces, inheriting method signatures from them, and promoting code reusability.

What is a real time example of multiple inheritance?

A real-time example of multiple inheritance is a class that inherits from both a "Vehicle" class and an "Electricity-Powered" class, to create a new class called "Electric Vehicle". This class would have access to both the properties and methods of its parent classes.

How multiple inheritance is achieved in Java?

Multiple inheritance is achieved in Java by using interfaces instead of classes. An interface is similar to a class it has variables and methods, however unlike a class, the methods in an interface are, by default abstract.

Why multiple inheritance is not possible in Java?

Java doesn't support multiple inheritance because it can lead to constructor chaining issues when a subclass implements two superclasses, ensuring simpler and more reliable code.

What is the limitation of multiple inheritance in Java?

Multiple inheritance in Java is the potential for conflicts and ambiguity when inheriting from multiple superclasses with same methods or fields name, leading to code complexity and the diamond problem.

Conclusion

In this article, we learned about multiple inheritance in Java. We have discussed why java does not support multiple inheritances and methods to implement multiple inheritance in Java.

We hope this blog increases your knowledge regarding Multiple Inheritance in Java. We recommend you to check out some of other interesting topics such as:

Happy learning!

Previous article
Multilevel Inheritance in Java
Next article
Abstraction In Java
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass