(Translated by https://www.hiragana.jp/)
Java and Multiple Inheritance - GeeksforGeeks
Open In App

Java and Multiple Inheritance

Last Updated : 16 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority. 

Note: Java doesn’t support Multiple Inheritance

Example 1:

Java




// Java Program to Illustrate Unsupportance of
// Multiple Inheritance
 
// Importing input output classes
import java.io.*;
 
//  Class 1
// First Parent class
class Parent1 {
 
  // Method inside first parent class
  void fun() {
 
    // Print statement if this method is called
    System.out.println("Parent1");
  }
}
 
// Class 2
// Second Parent Class
class Parent2 {
 
  // Method inside first parent class
  void fun() {
 
    // Print statement if this method is called
    System.out.println("Parent2");
  }
}
 
// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {
 
  // Main driver method
  public static void main(String args[]) {
 
    // Creating object of class in main() method
    Test t = new Test();
 
    // Trying to call above functions of class where
    // Error is thrown as this class is inheriting
    // multiple classes
    t.fun();
  }
}


Output: Compilation error is thrown

Conclusion: As depicted from code above, on calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Parent2’s fun() method. 

Example 2:

          GrandParent
           /     \
          /       \
      Parent1      Parent2
          \       /
           \     /
             Test

The code is as follows

Java




// Java Program to Illustrate Unsupportance of
// Multiple Inheritance
// Diamond Problem Similar Scenario
 
// Importing input output classes
import java.io.*;
 
//  Class 1
// A Grand parent class in diamond
class GrandParent {
 
  void fun() {
 
    // Print statement to be executed when this method is called
    System.out.println("Grandparent");
  }
}
 
// Class 2
// First Parent class
class Parent1 extends GrandParent {
  void fun() {
 
    // Print statement to be executed when this method is called
    System.out.println("Parent1");
  }
}
 
// Class 3
// Second Parent Class
class Parent2 extends GrandParent {
  void fun() {
 
    // Print statement to be executed when this method is called
    System.out.println("Parent2");
  }
}
 
// Class 4
// Inheriting from multiple classes
class Test extends Parent1, Parent2 {
 
  // Main driver method
  public static void main(String args[]) {
 
    // Creating object of this class i main() method
    Test t = new Test();
 
    // Now calling fun() method from its parent classes
    // which will throw compilation error
    t.fun();
  }
}


Output: 

Again it throws compiler error when run fun() method as multiple inheritances cause a diamond problem when allowed in other languages like C++. From the code, we see that: On calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Parent2’s fun() method. Therefore, in order to avoid such complications, Java does not support multiple inheritances of classes.

Multiple inheritance is not supported by Java using classes, handling the complexity that causes due to multiple inheritances is very complex. It creates problems during various operations like casting, constructor chaining, etc, and the above all reason is that there are very few scenarios on which we actually need multiple inheritances, so better to omit it for keeping things simple and straightforward.
  
How are the above problems handled for Default Methods and Interfaces
Java 8 supports default methods where interfaces can provide a default implementation of methods. And a class can implement two or more interfaces. In case both the implemented interfaces contain default methods with the same method signature, the implementing class should explicitly specify which default method is to be used in some method excluding the main() of implementing class using super keyword, or it should override the default method in the implementing class, or it should specify which default method is to be used in the default overridden method of the implementing class.

Example 3:

Java




// Java program to demonstrate Multiple Inheritance
// through default methods
 
// Interface 1
interface PI1 {
 
    // Default method
    default void show()
    {
 
        // Print statement if method is called
        // from interface 1
        System.out.println("Default PI1");
    }
}
 
// Interface 2
interface PI2 {
 
    // Default method
    default void show()
    {
 
        // Print statement if method is called
        // from interface 2
        System.out.println("Default PI2");
    }
}
 
// Main class
// Implementation class code
class TestClass implements PI1, PI2 {
 
    // Overriding default show method
      @Override
    public void show()
    {
 
        // Using super keyword to call the show
        // method of PI1 interface
        PI1.super.show();//Should not be used directly in the main method;
 
        // Using super keyword to call the show
        // method of PI2 interface
        PI2.super.show();//Should not be used directly in the main method;
    }
   
      //Method for only executing the show() of PI1
      public void showOfPI1() {
        PI1.super.show();//Should not be used directly in the main method;
    }
   
      //Method for only executing the show() of PI2
      public void showOfPI2() {
        PI2.super.show(); //Should not be used directly in the main method;
    }
 
    // Mai driver method
    public static void main(String args[])
    {
 
        // Creating object of this class in main() method
        TestClass d = new TestClass();
        d.show();
          System.out.println("Now Executing showOfPI1() showOfPI2()");
          d.showOfPI1();
          d.showOfPI2();
    }
}


Output

Default PI1
Default PI2
Now Executing showOfPI1() showOfPI2()
Default PI1
Default PI2

Note: If we remove the implementation of default method from “TestClass”, we get a compiler error. If there is a diamond through interfaces, then there is no issue if none of the middle interfaces provide implementation of root interface. If they provide implementation, then implementation can be accessed as above using super keyword.

Example 4:

Java




// Java program to demonstrate How Diamond Problem
// Is Handled in case of Default Methods
 
// Interface 1
interface GPI {
 
    // Default method
    default void show()
    {
 
        // Print statement
        System.out.println("Default GPI");
    }
}
 
// Interface 2
// Extending the above interface
interface PI1 extends GPI {
}
 
// Interface 3
// Extending the above interface
interface PI2 extends GPI {
}
 
// Main class
// Implementation class code
class TestClass implements PI1, PI2 {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Creating object of this class
        // in main() method
        TestClass d = new TestClass();
 
        // Now calling the function defined in interface 1
        // from whom Interface 2and 3 are deriving
        d.show();
    }
}


Output

Default GPI


Previous Article
Next Article

Similar Reads

Resolving Conflicts During Multiple Inheritance in Java
A class can implement multiple interfaces in java, but what if the implemented multiple default interfaces have default methods with the same signatures? Then in the implementing class, which of the default implementations would be invoked from the several parent interfaces. Java 8 designers have been thinking about this conflict and have specified
5 min read
How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class
2 min read
Why Java doesn't support Multiple Inheritance?
Multiple Inheritance is a feature provided by OOPS, it helps us to create a class that can inherit the properties from more than one parent. Some of the programming languages like C++ can support multiple inheritance but Java can't support multiple inheritance. This design choice is rooted in various reasons including complexity management, ambigui
5 min read
Multiple Inheritance in C++
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. The constructors of inherited classes are called in the same order in which they are inherited. For example, in the following program, B's constructor is called before A's constructor. A class can be derived from more than one base class. Eg: (i) A CHILD
5 min read
Difference between Inheritance and Composition in Java
Inheritance: When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself. A subclass inherits all the members (fields, methods, and nested
3 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class. Example
3 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes
3 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 min read
Java | Inheritance | Question 1
Output of following Java Program? class Base { public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } public class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Derived::sh
1 min read
Java | Inheritance | Question 2
class Base { final public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived();; b.show(); } } (A) Base::show() called (B) Derived::show() called
1 min read
Java | Inheritance | Question 3
Java Code class Base { public static void show() { System.out.println("Base::show() called"); } } class Derived extends Base { public static void show() { System.out.println("Derived::show() called"); } } class Main { public static void main(String[] args) { Base b = new Derived(); b.show(); } } (A) Base::show() called (B) Deriv
1 min read
Java | Inheritance | Question 4
Which of the following is true about inheritance in Java? 1) Private methods are final. 2) Protected members are accessible within a package and inherited classes outside the package. 3) Protected methods are final. 4) We cannot override private methods. (A) 1, 2 and 4 (B) Only 1 and 2 (C) 1, 2 and 3 (D) 2, 3 and 4 Answer: (A) Explanation: See http
1 min read
Java | Inheritance | Question 5
Output of following Java program? class Base { public void Print() { System.out.println("Base"); } } class Derived extends Base { public void Print() { System.out.println("Derived"); } } class Main{ public static void DoPrint( Base o ) { o.Print(); } public static void main(String[] args) { Base x = new Base(); Base y = new Deri
1 min read
Java | Inheritance | Question 9
Predict the output of following program. Note that foo() is public in base and private in derived. class Base { public void foo() { System.out.println("Base"); } } class Derived extends Base { private void foo() { System.out.println("Derived"); } } public class Main { public static void main(String args[]) { Base b = new Derived
1 min read
Java | Inheritance | Question 7
Which of the following is true about inheritance in Java. 1) In Java all classes inherit from the Object class directly or indirectly. The Object class is root of all classes. 2) Multiple inheritance is not allowed in Java. 3) Unlike C++, there is nothing like type of inheritance in Java where we can specify whether the inheritance is protected, pu
1 min read
Java | Inheritance | Question 8
Predict the output of following Java Program // filename Main.java class Grandparent { public void Print() { System.out.println("Grandparent's Print()"); } } class Parent extends Grandparent { public void Print() { System.out.println("Parent's Print()"); } } class Child extends Parent { public void Print() { super.super.Print();
1 min read
Java | Inheritance | Question 9
final class Complex { private final double re; private final double im; public Complex(double re, double im) { this.re = re; this.im = im; } public String toString() { return "(" + re + " + " + im + "i)"; } } class Main { public static void main(String args[]) { Complex c = new Complex(10, 15); System.out.println(
1 min read
Output of Java program | Set 23 (Inheritance)
Prerequisite: Inheritance in Java 1) What is the output of the following program? Java Code public class A extends B { public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing()); } } class B { public static String sing() { retu
3 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
What is the Need of Inheritance in Java?
Inheritance, as we have all heard is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is the need for Inheritance? Why is it so an important concept Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e. data members)
6 min read
Using final with Inheritance in Java
Prerequisite - Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. Using final with inheritance During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throug
4 min read
Object Serialization with Inheritance in Java
Prerequisite: Serialization, Inheritance Serialization is a mechanism of converting the state of an object into a byte stream. The byte array can be the class, version, and internal state of the object. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persis
6 min read
Delegation vs Inheritance in Java
Inheritance in Java programming is the process by which one class takes the property of another other class. i.e. the new classes, known as derived or child class, take over the attributes and behavior of the pre-existing classes, which are referred to as base classes or super or parent class.Delegation is simply passing a duty off to someone/somet
3 min read
Favoring Composition Over Inheritance In Java With Examples
In object-oriented programming (OOP), choosing between inheritance and composition is crucial for designing flexible and maintainable code. This article explores why you should favor composition over inheritance, with simple explanations and examples. What is Inheritance?Inheritance is when a new class is based on an existing class. The new class (
3 min read
Inheritance in Java
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of tha
13 min read
OOP in Python | Set 3 (Inheritance, examples of object, issubclass and super)
We have discussed following topics on Object Oriented Programming in Python Object Oriented Programming in Python | set-1 Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing) In this article, Inheritance is introduced. One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanis
4 min read
Hibernate - Inheritance Mapping
The inheritance hierarchy can be seen easily in the table of the database. In Hibernate we have three different strategies available for Inheritance Mapping Table Per HierarchyTable Per Concrete classTable Per Subclass Hierarchy can be diagrammatically seen easily. In this article let us see about Table Per Hierarchy using XML. It can be done using
5 min read
Hibernate - @Inheritance Annotation
The @Inheritance annotation in JPA is used to specify the inheritance relation between two entities. It is used to define how the data of the entities in the hierarchy should be stored in the database. The @Inheritance annotation provides us with benefits to reduce code complexity by creating a base class and inheriting other classes from the base
6 min read
Practice Tags :