Why Multiple Inheritance Is Not Supported In Java And We Can Do So?

Here we will find out Why Multiple Inheritance is not supported in Java And We can do so? As multiple inheritances lead to ambiguity errors so to prevent it is not being allowed in java, using a class but we can perform it using the interface that we will discuss here in detail.

Inheritance

Why Multiple Inheritance is not supported in Java?

As we know in multiple inheritances we inherited the properties from two different classes in one class and that could create certain problems that we are going to understand here in detail.

class Class1{
      public void display(){
            System.out.println("Display method inside Class1.");
      }
}
 
class Class2{
      public void display(){
            System.out.println("Display method inside Class2.");
      }
}
 
//let multiple inheritance is possible.
public class Test extends Class1, Class2{
      public static void main(String args[]){
            Test obj = new Test();
            //Ambiguity problem in method call which class display() method will be called.
            obj.display();
      }
}

As we can see the class test is inherited from class1 and class2 and the class test has an object as obj it is called a function display which is there in both the parent classes so now which function will be called is the condition that we call ambiguity.

And to prevent such conditions we do not have multiple inheritances in java.

Now lets understand

How We Can Implement Multiple Inheritance?

We can implement multiple inheritances using Interface to understand this follow the code given below and understand how we can do so.

interface Interface1
{
   public void show();
}
interface Interface2
{
   public void show();
}
class SubClass implements Interface1, Interface2
{
   public void show()
   {
       System.out.println("A class can implements more than one interfaces");
   }
   public static void main(String args[]){
    SubClass obj = new SubClass();
    obj.show();
   }
}

here subclass has an inheritance of both the interfaces interface1 and interface2 and we can call the function of interfaces using the object of subclass and there will not be any error. As there is no body of the abstract function and every function of the interface is purely abstract.

Learn More about it at Multiple Inheritance using the interface https://dev.to/kuljeet/multiple-inheritance-in-java-1fmo#:~:text=The%20only%20way%20to%20implement,interfaces%20are%20implemented%20in%20class.

And also visit Java Tutorials By Prakhar Yadav to learn more about java and solve the problems related to java and also visit Replacements For Switch Statement In Python? for python tutorials and other programming related problems.

 

Leave a Comment

%d bloggers like this: