Tutorial

Multiple Inheritance in Java: Explained with Examples and Best Practices

Updated on February 14, 2025
Multiple Inheritance in Java: Explained with Examples and Best Practices

Introduction

Inheritance is one of the fundamental principles of Object-Oriented Programming (OOP) that allows one class (the child class or subclass) to inherit fields and methods from another class (the parent class or superclass). This promotes code reuse, modularity, and better maintainability.

In this article, we will deep-dive into the concept of multiple inheritance in Java, building upon previous tutorials on inheritance, interface, and composition in Java.

How to Implement Inheritance in Java

Inheritance in Java is implemented using the extends keyword. Here’s an example:

// Parent class
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// Child class inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.makeSound(); // Inherited method
        dog.bark(); // Child class method
    }
}

This example demonstrates single inheritance, where the Dog class inherits behavior from the Animal class.

Different Types of Inheritance in Java

Java supports different types of inheritance, which define the relationships between classes. These include:

  1. Single Inheritance: A subclass inherits from a single parent class.

    For example:

    // Parent class
    class Animal {
       void makeSound() {
          System.out.println("Animal makes a sound");
       }
    }
    
    // Child class inheriting from Animal
    class Dog extends Animal {
       void bark() {
          System.out.println("Dog barks");
       }
    }
    
  2. Multilevel Inheritance: A subclass derives from another subclass, forming a hierarchy.

    For example:

    // Grandparent class
    class Animal {
       void makeSound() {
          System.out.println("Animal makes a sound");
       }
    }
    
    // Parent class inheriting from Animal
    class Mammal extends Animal {
       void eat() {
          System.out.println("Mammal eats");
       }
    }
    
    // Child class inheriting from Mammal
    class Dog extends Mammal {
       void bark() {
          System.out.println("Dog barks");
       }
    }
    
  3. Hierarchical Inheritance: Multiple classes inherit from the same parent class.

    For example:

    // Parent class
    class Animal {
       void makeSound() {
          System.out.println("Animal makes a sound");
       }
    }
    
    // Child class 1 inheriting from Animal
    class Dog extends Animal {
       void bark() {
          System.out.println("Dog barks");
       }
    }
    
    // Child class 2 inheriting from Animal
    class Cat extends Animal {
       void meow() {
          System.out.println("Cat meows");
       }
    }
    
  4. Hybrid Inheritance: A mix of two or more types of inheritance. Java does not support direct hybrid inheritance but can be achieved using interfaces. Here’s an example:

    // Interface 1
    interface Flyable {
       void fly();
    }
    
    // Interface 2
    interface Walkable {
       void walk();
    }
    
    // Parent class
    class Animal {
       void makeSound() {
          System.out.println("Animal makes a sound");
       }
    }
    
    // Child class inheriting from Animal and implementing Flyable and Walkable
    class Bird extends Animal implements Flyable, Walkable {
       @Override
       public void fly() {
          System.out.println("Bird flies");
       }
    
       @Override
       public void walk() {
          System.out.println("Bird walks");
       }
    }
    

For a deeper dive into OOP concepts in Java, check this tutorial on OOPS Concepts in Java - OOPS Concepts Example.

Performance Considerations of Inheritance in Java

While inheritance promotes code reuse, it can impact memory usage and performance if not used wisely. Key considerations include:

  • Memory Consumption: Each subclass instance contains data from both the subclass and superclass, leading to increased memory consumption.

  • Method Resolution: The JVM must resolve method calls dynamically, which might introduce slight overhead in method lookup.

  • Deep Inheritance Trees: Excessive inheritance levels can lead to a complex class hierarchy, making debugging and performance tuning difficult.

For performance-critical applications, consider alternatives like composition, which often provides better flexibility and maintainability.

FAQ

1. What is inheritance in Java?

Inheritance in Java is a mechanism where a subclass derives properties and behaviors from a parent class, allowing for code reuse and hierarchical structuring. You can read more about inheritance in this tutorial on Inheritance in Java.

2. What are the types of inheritance in Java?

Java supports single, multilevel, hierarchical, and hybrid inheritance. However, multiple inheritance is not supported directly due to the diamond problem.

3. How does the extends keyword work in Java?

The extends keyword is used to indicate that a class is inheriting from another class. The child class gains access to the parent class’s methods and fields. Here’s an example:

// Parent class
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// Child class inheriting from Animal
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

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

Inheritance defines a “is-a” relationship, while composition represents a “has-a” relationship. Composition is often preferred for better flexibility. Read more about the differences in this tutorial on Composition vs Inheritance.

Concept Inheritance Composition
Relationship “is-a” “has-a”
Flexibility Less flexible More flexible
Code Reuse Promotes code reuse Promotes code reuse
Complexity Can lead to tight coupling Encourages loose coupling

5. Can a subclass override a method in Java?

Yes, a subclass can override a method from the parent class using the @Override annotation. This allows the subclass to provide a specific implementation of the inherited method.

Here’s an example:

// Parent class
class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

// Child class inheriting from Animal
class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog makes a sound");
    }
}

6. Why does Java not support multiple inheritance?

Java does not support multiple inheritance for classes to prevent ambiguity and diamond problems. This decision was made to ensure that the language remains simple and easy to use, avoiding the complexities that can arise from multiple inheritance. However, multiple inheritance can be achieved using interfaces, which provide a way to implement multiple behaviors without the risks associated with multiple inheritance.

7. When should I avoid using inheritance in Java?

Avoid inheritance when:

  • A deep inheritance hierarchy complicates maintenance.
  • Code reuse can be better achieved with composition.
  • There is no clear is-a relationship between classes.

Conclusion

Understanding inheritance and its best practices ensures that your Java applications remain efficient, modular, and easy to maintain. By balancing inheritance and composition, you can achieve a well-structured application.

You can learn more about object-oriented programming in this tutorial on OOPS concept in Java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 21, 2013

Bit confused. “favor composition over interfaces” or “favor composition over inheritance”?.

- Super Hubo

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 21, 2013

Thanks for catching the typo error, corrected it.

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 7, 2014

    good explanation…

    - subbareddy

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      February 6, 2014

      What is association in Java?

      - Madhusmita Nayak

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 30, 2014

        How the multiple inheritance is possible in C , C++ but not in java can u explain the context…

        - Elumalai

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 13, 2015

        class A{ void method1(){} }; class B{ void method2(){} }; class C: public A, public B{ } //////////////////////////// Now C have both methods … method1 and method 2… that’s multiple inheritance in C++, but java not allowed it.

        - Asif Mushtaq

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          June 25, 2014

          How the multiple inheritance is possible in C , C++ but not in java can u explain the context…

          - Suman

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 28, 2014

            Can u give examples/Complete class defintions to proove your 2nd & 3rd point of Composition better than inheritance.??

            - Sorrowfull Blinger

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              February 12, 2016

              Suppose we have a superclass and subclass as follows: ClassC.java 1 2 3 4 5 6 7 package com.journaldev.inheritance; public class ClassC{ public void methodC(){ } } ClassD.java 1 2 3 4 5 6 7 8 package com.journaldev.inheritance; public class ClassD extends ClassC{ public int test(){ return 0; } } The above code compiles and works fine but what if ClassC implementation is changed like below: ClassC.java 1 2 3 4 5 6 7 8 9 10 package com.journaldev.inheritance; public class ClassC{ public void methodC(){ } public void test(){ } }Suppose we have a superclass and subclass as follows: ClassC.java 1 2 3 4 5 6 7 package com.journaldev.inheritance; public class ClassC{ public void methodC(){ } } ClassD.java 1 2 3 4 5 6 7 8 package com.journaldev.inheritance; public class ClassD extends ClassC{ public int test(){ return 0; } } The above code compiles and works fine but what if ClassC implementation is changed like below: ClassC.java 1 2 3 4 5 6 7 8 9 10 package com.journaldev.inheritance; public class ClassC{ public void methodC(){ } public void test(){ } } I think this not the problem after Jdk 1.5 where we can have different return types for both overriding and overidden methods in the parent and subclass.

              - safdar

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 21, 2016

                composition has its limitations. I believe composition is an option as long as the classes and their methods we want to consume are “public”. In case we want to access “protected” members you have to fall back on either Interfaces or Classes. Not denying - composition is a useful means and improves our code refactoring skills.

                - Yunus Atheist

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  December 27, 2016

                  There are many advantages of using composition, couple of them are : You will have full control of your implementations. i.e., you can expose only the methods you intend to expose. any changes in the super class can be shielded by modifying only in your class. Any clients classes which uses your classes, need not make modifications. Allows you to control when you want to load the super class (lazy loading)

                  - Mayank

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    May 6, 2017

                    You are awesome Pankaj.

                    - Ravi Verma

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      June 22, 2017

                      You are awesome Pankaj.

                      - Yashvir Singh

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        August 30, 2017

                        Can you please explain the example given in point 3, public ClassC(SuperClass o){ this.obj = o; } . . . ClassC obj1 = new ClassC(new ClassA()); ClassC obj2 = new ClassC(new ClassB()); How can this be achived?

                        - T sinha

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          October 10, 2017

                          sir u do not discuss abstract class before.if u take example like this how student will understand

                          - subrat

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            June 9, 2018

                            Hi, We can change the access specifier as private test() method of ClassC and we again declare the same method as public in ClassD, It Will compile without error. It’s doesn’t matter return type as well. public class ClassC{ public void methodC() { } private void test() { } } public class ClassD extends ClassC { public int test() { return 0; } }

                            - Paresh Sojitra

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 2, 2018

                              how we can achieve composition in abstract class?

                              - varsha

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              April 28, 2019

                              make the attribute of class Is Private. like… this is our abstract class package com.abstractvthinheritance; public abstract class Engine { public abstract int startMode(int mode); } NOTE:-- Provide the Implementation of Abstract class implementing Composition Code below:- package com.abstractvthinheritance; public class Car { private Engine engine;//Composition // which makes our code to testable and we can use at the basis of modularity Car(Engine engine){ this.engine=engine; } public int drive(int mode) { int outCome = 0; outCome=engine.startMode(0); if (outCome==0) { System.out.println(“Accelereate the Car and Drive”); }else if (outCome ==1) { System.out.println("Need to Try again "); }else if (outCome ==2) { System.out.println("Need Maintenace of Engine "); }else if (outCome == 3) { System.out.println("failed to start "); } return 0; } } This way we can implement Composition

                              - Amar Kumar

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 9, 2019

                              public class Car missing extends Engine how can it implement Engine ?

                              - kopid

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                October 26, 2018

                                Hi everyone the explained multiple inheritance concept is wrong. first thing is we cannot extend two classes , there itself we get compile time error. the correct answer for "why multiple inheritance is not possible in java " is. every class contains constructor , if user is not defined the constructor compiler itself will define the constructor and internally the super class constructor is called by super() calling statement and we cannot have 2 super() calling statements and when we extend 2 class to one class there will be an ambiguity for sub class constructor that is , for which class it should call. but interface doesn’t contain constructor so it can be achieved through interface.

                                - Chandra Shekar Gowda M

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                October 26, 2018

                                Hi Chandra, I am not sure if you read the complete post, I have clearly mentioned in bold that “Java doesn’t provide support for multiple inheritances in classes.” Secondly, I have explained about one of the main reason as being the diamond problem. What you are suggesting with super() also falls in the same category. If creators of Java would have wanted to support multiple inheritances, they would have found some workaround to all these issues. Java by design doesn’t support multiple inheritances with classes, just as some other programming languages support it by design. It was a choice made by the creators of Java and we are just showing the possible reasons to do that.

                                - Pankaj

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  November 6, 2019

                                  I think this is not right at all… Then what will happen if you explicitly call both the super class constructors… Even then it’ll not work… Ross answer is wrong

                                  - Anton Milan

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    November 16, 2018

                                    “ClassC extends ClassA, ClassB” - excuse me? :)

                                    - Daniel

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    January 10, 2019

                                    I Agree. Very True. Impossible. Java Has NO Diamond problem whatsoever.

                                    - Surya

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    January 10, 2019

                                    Please read the text before the code. This is just to show what can happen if java classes can extend more than one concrete classes.

                                    - Pankaj

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    January 10, 2019

                                    Thank you. Now I see what you mean. You mentioned: “To understand diamond problem easily, let’s assume that multiple inheritance was supported in java.” Must have highlighted “let’s assume”. It skips mind easily otherwise. Thanks again.

                                    - Surya

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      January 10, 2019

                                      The author Pankaj has mentioned assumption: To understand diamond problem easily, “let’s assume” that multiple inheritance was supported in java. Pankaj is right in trying to explain the concept. He already mentioned: Java doesn’t support multiple inheritance in classes because it can lead to diamond problem. Pankaj can you please assert that there is no diamond problem because java has no multiple inheritance in the first paragraph. So that way now one is carried away. Thanks in advance.

                                      - Surya

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        January 18, 2019

                                        interface a1 { int a=1; } interface b1 { int a=2; } class a implements a1,b1 { print (a) } what values of a will print in case of multiple inheritance

                                        - shubhada

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        January 18, 2019

                                        Error: reference to a is ambiguous…

                                        - Pankaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          March 13, 2020

                                          Interface 2

                                          - Shiv D

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            January 23, 2019

                                            Thanks Pankaj, Good Explanation…,

                                            - Narendar

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              January 28, 2019

                                              Multiple inheritance in Java is possible (although in limited way) since java 8, using default method of the interface

                                              - Victor

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                February 16, 2019

                                                Two interfaces A and B having two same name method or different name methods without any definition. a class C is implementing methods from Interface A and B and giving definitions to those methods and we call it multiple inheritance. ??? ------------- HOW ? -------------- ??? interface A { public void method_A(); } interface B { public void method_B(); } Class C implements A,B { public void method_A() { System.out.println(“does not make any sense”); } public void method_B() { System.out.println(“This one too is useless”); } public void thisone() { System.out.print(“Both methods method_A() and method_B() can be declared and defined in class C”); System.out.println(“then what is the use of interface”); } } Can’t we declare those methods in Class C without any interface. If multiple inheritance is not possible in Java then we should not try it, above examples are just misleading the interface concepts, interfaces are used to achieve design pattern problems e.g Adapter pattern.

                                                - joker

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  February 11, 2020

                                                  Thank You Sir… This is Great Explanation

                                                  - Muhammad

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    June 20, 2020

                                                    thanks, Pankaj. found this very useful

                                                    - VIN-ANUONYE CHUKWUEMEKA

                                                      Try DigitalOcean for free

                                                      Click below to sign up and get $200 of credit to try our products over 60 days!

                                                      Sign up

                                                      Join the Tech Talk
                                                      Success! Thank you! Please check your email for further details.

                                                      Please complete your information!

                                                      Become a contributor for community

                                                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                      DigitalOcean Documentation

                                                      Full documentation for every DigitalOcean product.

                                                      Resources for startups and SMBs

                                                      The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                      Get our newsletter

                                                      Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                      New accounts only. By submitting your email you agree to our Privacy Policy

                                                      The developer cloud

                                                      Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                      Get started for free

                                                      Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                      *This promotional offer applies to new accounts only.