Multiple Inheritance in Java

Multiple Inheritance in Java

Have you ever thought that a class in Java can have more than one parent? This is a common question, especially if you have seen languages like C++ that allow multiple inheritance. In Java, multiple inheritance with classes is not allowed because it can create confusion when two parent classes have the same method. However, Java provides a smart solution – it allows multiple inheritance through interfaces. This way, a class can still use features from many sources without any problems. This design keeps your code readable and reduces the chances of ambiguity or errors.

In this article, we will explore multiple inheritance with real-world examples in detail.

Table of Contents:

What is Inheritance in Java?

Inheritance in Java is a mechanism where one child class or subclass inherits the properties and behaviors of another parent class or a superclass, i.e., a child class can use the methods and variables of a parent class. It allows one to reuse the code and build relationships between the classes. Java supports single inheritance, meaning a class can inherit from only one superclass directly.

Syntax:

class Parent {
    // parent class members
}

class Child extends Parent {
    // child class members
}

As above, the child class extends a Parent class, hence, it can use the variables and methods that are defined in the parent class.

Types of Inheritance in Java

Java allows different types of inheritance that can be used with classes to increase the reusability of the code. Some of them are discussed below.

Types of Inheritance in Java

1. Single Inheritance in Java

In single inheritance, a subclass inherits the properties and behaviors of only one superclass. It is the simplest and most commonly used form of inheritance in Java. Below is the syntax of single inheritance in Java.

class Parent {
    // parent members
}

class Child extends Parent {
    // child members
}

2. Multilevel Inheritance in Java

In multilevel inheritance, a class is derived from a derived class, i.e., it forms a chain of inheritance where each class adds the behaviors from its previous class. Below is the syntax of multilevel inheritance in Java.

class Grandparent {
    // grandparent members
}

class Parent extends Grandparent {
    // parent members
}

class Child extends Parent {
    // child members
}

3. Hierarchical Inheritance in Java

In hierarchical inheritance, multiple classes inherit from a single superclass, i.e., it is like a tree structure where one base class has many branches into its child classes. Below is the syntax of hierarchical inheritance in Java.

class Parent {
    // parent members
}

class Child1 extends Parent {
    // child1 members
}

class Child2 extends Parent {
    // child2 members
}

4. Hybrid Inheritance in Java

Hybrid inheritance is a mix of two or more types of inheritance, i.e., it is a combination of hierarchical and multiple inheritance, and is supported by using the interfaces only, not with the classes. Below is the syntax of hybrid inheritance in Java.

interface A {
    // members
}

interface B extends A {
    // members
}

interface C {
    // members
}

class D implements B, C {
    // members
}

5. Multiple Inheritance in Java

Multiple inheritance in Java is not supported with classes, i.e., one class extending two classes directly, because it leads to ambiguity, known as the diamond problem. Below is the syntax of multiple inheritance in Java.

class A {
    void display() { }
}

class B {
    void display() { }
}

// Not allowed
// class C extends A, B { } // Compile-time error

Now, let us understand what multiple inheritance is in Java.

Get 100% Hike!

Master Most in Demand Skills Now!

What is Multiple Inheritance in Java?

Multiple Inheritance in Java is a situation where a class inherits the features of more than one parent class. The concept allows a class to reuse functionality from multiple sources. Java does not support multiple inheritance with classes, and if you try to extend more than one class, the compiler will throw an error.

What is Multiple Inheritance in Java ?

For example, if Class C inherits from both Class A and Class B, it can use methods from both classes without rewriting them, which is not allowed in Java.

class A {
    void greet() {
        System.out.println("Hello from A");
    }
}

class B {
    void greet() {
        System.out.println("Hello from B");
    }
}

// Java doesn't allow this
class C extends A, B {
    // Error: Class cannot extend multiple classes
}

Why is Multiple Inheritance Not Supported in Java?

Multiple inheritance in Java is not supported because of the Java Diamond Problem. Let us discuss what the Diamond Problem is in detail.

Java Diamond Problem

The Diamond Problem is a famous problem in object-oriented programming that occurs with multiple inheritance, i.e., when a class is inherited from two classes that have a common superclass.

For example,

class A {
    void display() {
        System.out.println("A's display");
    }
}

class B extends A { }

class C extends A { }

// Not allowed in Java
// class D extends B, C { } // Compile-time error

Now, let us understand the above code in visual form.

    A
   / 
  B   C
    /
    D

In the above example

  • Classes B and C inherit from class A.
  • Class D inherits from both B and C.

Now, if class A has a method display() and B and C do not override it. As a result, class D would inherit two ambiguous versions of the display() method, one from B and another from C.

How Does Multiple Inheritance Work in Java?

Multiple Inheritance means a class can inherit the features from more than one parent class. In languages like C++, multiple inheritance is allowed with classes, but in Java, it is not allowed with classes because of ambiguity issues like the Diamond Problem.

In Java, Multiple inheritance-like features can only be achieved by Interfaces. Before Java 8, interfaces could only have method names, i.e., no code, so there was no chance of a conflict. If a class has implemented the two interfaces, it just had to write the code for each method, and everything worked smoothly. But from Java 8 onward, interfaces can also have default methods that can have both a name and some code inside them. This can lead to confusion if two interfaces have the same default method name.

To solve this problem, Java mandates that if a class implements two interfaces having the same default method, the class has to override that method and provide its own version.

Inside the JVM, Java handles all this by making a list of methods for each class, which helps the computer to quickly find the correct method and run it. And for each class, Java creates a single object per class instance, which makes the program run efficiently and avoids unnecessary memory usage.

Java follows a simple rule, if a class and an interface both have the same method with the same name, Java will always use the method of the class, not of the interface. This rule avoids the confusion between the names of the method.

Implementation of Multiple Inheritance in Java

Multiple inheritance in Java can be implemented only by using interfaces, and not by classes. Java allows a class to implement multiple interfaces using the implements keyword because interfaces only declare the methods without implementation, unless they are marked default. Hence, there is no confusion about the behavior of the method.

Multiple inheritance in Java example:

Java

Output:

Multiple inheritance in Java example

Explanation:

In the above Java program, there are 2 interfaces, Printable and Showable. The class MyClass is implementing both the interfaces and then overriding their methods. In the main method, the object of the MyClass is made, and then the 2 interfaces are called.

Real-World Applications of Multiple Inheritance

  • 1. Mobile Notification Systems
    A mobile app that sends notifications, like alarms, can implement multiple interfaces like Schedulable, Notifiable, and Configurable, which helps the app to manage timing, displaying notifications, and preferences of the user in one class.
  • 2. E-Commerce Platforms
    In shopping apps, a ProductManager class can implement interfaces like Searchable, Filterable, and Reviewable, which means it can search the products, apply filters like price or brand, and also handle the reviews of the product.
  • 3. AI Chatbots and Voice Assistants
    A virtual assistant like Alexa or Google Assistant can implement interfaces like Speakable, Understandable, and Learnable, which allow it to speak, understand the commands, and learn from previous interactions.
  • 4. Gaming Platforms
    In a multiplayer game, the class MultiplayerGame can implement the interfaces like Playable, ScoreTrackable, and Networkable, which will help it to manage the player scores and online connections of more than one player.
  • 5. Ride-Sharing Apps
    Apps like Uber or Ola can have a class DriverApp that implements the interfaces like Trackable, Routable, and PaymentCapable, which will track the location of the driver, calculate trip routes, and process payments

Conclusion

From the above article, we conclude that multiple inheritance is a concept in which a class can use the features from more than one class. Java does not allow multiple inheritance because it creates confusion, like the diamond problem. But Java allows you to implement multiple interfaces, which makes your code more flexible, reusable, and organized. It has many real-world applications, including mobile apps and games, to hospital systems and e-commerce platforms. Many real-world systems use multiple interfaces to use different features in one class. By understanding and applying this concept, developers can build more modular and maintainable applications in Java.

If you want to learn more about this topic, you can refer to our Java course.

Multiple Inheritance in Java – FAQs

Q1. What are the types of inheritance in Java?

Java jas single, multilevel, hierarchical, and hybrid inheritance, but it does not allows multiple inheritance.

Q2. Why does Java remove multiple inheritance?

Java removes multiple inheritance to avoid the ambiguity that comes with it.

Q3. What is the difference between inheritance and composition in Java?

Inheritance shows an is-a relationship, like a Dog is an Animal, and Composition shows a has-a relationship, like a Car has an Engine.

Q4. Can a subclass override a method in Java?

Yes, a subclass can override the methods from its parent class to provide the specific behavior.

Q5. When should I avoid using inheritance in Java?

Inheritance in Java should be used when the classes are not closely related or when the composition offers better flexibility.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner