Multiple Inheritance in Java

Multiple Inheritance in Java
Multiple Inheritance in Java

Introduction

What comes to your mind when you first hear the word Inheritance

Doesn’t it remind you of how someone at a family gathering said that you inherited your mother’s eyes or father’s hair?

Well, that’s what inheritance is, even in programming. In other words,


Inheritance is the process in which a derived class derives attributes and methods from a base class. 

Considering our previous example, the following picture shows inheritance.


There are different types of Inheritance in Java like Single Inheritance, Multilevel Inheritance in Java, Multiple inheritance, Hierarchical Inheritance in Java, and Hybrid Inheritance. In this article, we’ll be learning about Multiple Inheritance in Java in particular. 

Multiple Inheritance

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.  


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

To formally define it,

Multiple inheritance is the process in which a single derived class inherits attributes and functions from multiple base classes. 


Let’s see this with the help of a program.

//Parent class 1
class ParentClass1  
{
void text()
    {
          System.out.println("Inside parent class 1!!");
    } 
} 
//Parent class 2
class ParentClass2  
{
    void text()
    {
          System.out.println("Inside parent class 2!!");
    } 
}
//Child class trying to inherit two parent classes
class Child extends ParentClass1, ParentClass2
{
public static void main(String args[])
    { 
//creating object of child class
Child obj=new Child(); 
//ambiguity
        obj.text();
    }  
}

You may have noticed that both the parent classes in the code above contain the same method text( ). So, when the child class calls this method, which text( ) method is invoked?

With this ambiguity, we come to an essential fact about Multiple Inheritance in Java.

Unlike C++ and Python, multiple inheritance is not supported in Java. 

Source: giphy

Let us see the reason behind this. 

Why Java Does Not Support Multiple Inheritance

We already saw that there is an ambiguity with Multiple Inheritance in Java in our code above. On executing the above ambiguous code, we get the below output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

at Child.main(Child.java:20)

The above program does not compile successfully, as evidenced by the output. The compiler gets confused while mapping the function call with the definition, leading to a compile-time error. That’s why multiple inheritance in Java is not supported.

You can refer to the diagram below to understand it better.

Wondering how C++ accomplishes this?

C++ uses two ways to avoid this ambiguity. 

  1. To manually specify the class whose fields will be accessed, a scope resolution operator is used.
  2. To remove multiple copies of a base class, it uses the concept of the virtual class.

However, Java being one of the best languages provides a backdoor to implement multiple inheritance. Let us see what it is next. 

An Alternative to 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, but what is an Interface?

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. 

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

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

class C implements A,B
{

    public void text()   //Default method in interface is overriden
    {
  A.super.text();  //text() method from first interface is called
  B.super.text();  //text() method from second interface is called
    }
}

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. 

interface A   // Interface 1
{
public abstract void text1();    // Abstract method
}

interface B   // Interface 2
{
public abstract void text2();   // Abstract method
}

class C implements A,B   // Interface is implemented
{
      // 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)
{
    C obj = new C(); // Create a C object
    obj.text1();
    obj.text2();
}
}

Output:

HelloWhat’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.

Frequently Asked Questions

What is multiple inheritance in Java?

Multiple inheritance is the process in which a single derived class inherits attributes and functions from multiple base classes.

Why Doesn’t Java Support Multiple Inheritance?

In multiple inheritance, if any two base classes have methods with the same name, then while calling the method, there is a problem with which method will be called. To avoid this complexity, Java has no multiple inheritance.

How does Java provide multiple inheritance?

Multiple inheritance is provided in Java by using interfaces instead of classes.

What are the types of inheritance?

The different types of inheritance are:
Single inheritance
Multilevel inheritance
Multiple inheritance
Hierarchical inheritance
Hybrid inheritance

Difference between a class and an interface.

Class
The “class” keyword is used to create a class.
They can be instantiated (objects can be created) and hence contain constructors.
In Java, they do not support multiple inheritances.
A class can inherit an interface and another class.
They are inherited using the “extends” keyword.
They cannot have abstract methods.
Variables and methods can be declared using any access specifier.
Variables can be static, final or neither.

Interface
The “interface” keyword is used to create an interface.
They cannot be instantiated (objects cannot be created) and hence cannot contain constructors.
They support multiple inheritances in Java.
An interface cannot inherit a class but can inherit another interface.
They are inherited by a class using the “implements” keyword and another interface using the “extends” keyword.
They have abstract methods only.
Variables and methods must be declared as public only.
Variables are either static or final.

Key Takeaways

In this article, we learned about multiple inheritance in Java, but there are other types of inheritance too. Namely, they are:

  • Single inheritance
  • Multilevel inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Hybrid inheritance

Once we know about them, too, we will have a complete understanding of Inheritance in Java. This will cover an important theoretical topic. Apart from that, we must enhance our coding skills by rigorously practising coding questions commonly asked in interviews. Such questions can be found at CodeStudio. Other than coding questions, you will also find the interview experience of scholars in renowned product-based companies. 

Happy learning!

By: Neelakshi Lahiri

Exit mobile version