Types Of Inheritance In Java – Single Vs Multiple Inheritance

Learn all about the various types of inheritance in Java with the help of simple examples. Find out if Java supports multiple inheritance:

We introduced Inheritance in Java along with the various basic concepts related to inheritance to the readers in our last tutorial.

In this tutorial, we will explore further into the inheritance topic and learn more about the types of inheritance.

=> Check ALL Java Tutorials Here.

Types of Inheritance in Java

Types Of Inheritance In Java

Depending on the way the classes are inherited and how many classes are inherited, we have the following types of inheritance as shown in the below figure.

types of inheritance

As shown in the above figure, there are five types of inheritances in Object-Oriented programming as described below:

#1) Single Inheritance: When a derived class or subclass inherits from only one base or superclass then it is single inheritance.

#2) Multilevel Inheritance: In Multilevel Inheritance, we have more than one level wherein a class inherits from a base class and the derived class in turn is inherited by another class.

#3) Hierarchical Inheritance: An inheritance hierarchy is formed in this type of inheritance when a superclass is inherited by more than one class.

#4) Multiple Inheritance: Multiple inheritance is the one in which a class can inherit properties and behavior from more than one parent.

#5) Hybrid Inheritance: When one or more types of inheritance are combined, then it becomes a hybrid inheritance.

Note that Java supports only single, multilevel, and hierarchical type of inheritance using classes. Java does not support multiple and hybrid inheritance with classes.

Now we will discuss each type of inheritance in detail with programming examples.

Single Inheritance In Java

A single inheritance is depicted as shown below:

Single inheritance in Java

Here a subclass inherits from a single superclass. This is single inheritance. Any animal like Dog inherits from the Animal species. This is the simplest form of inheritance.

Given below is a Java program that explains Single Inheritance.

//base class:Animal
class Animal
{  
    void Action_eat()
    {
        System.out.print("eating...");
    }  
}  
//derived class:Dog
class Dog extends Animal
{  
    void Action_bark()
    {
        System.out.print("barking...");
        
    }  
}  
class Main{  
    public static void main(String args[]){  
        Dog d=new Dog();    //create an object of derived class  
        System.out.print("The dog is ");
        d.Action_bark();    //call derived class method
        System.out.print("\nThe dog is ");
        d.Action_eat();     //call base class method
    }
}  

Output:

single inheritance example

Here, we have one method eat (Action_eat) in base class Animal which is common to Animal species. We have a derived class Dog that derives from Animal class. In the Dog class, we have a method specific to Dog species, bark (Action_bark).

Then we create a Dog object in the main method and as the Dog class has inherited the Animal class, this object can call eat as well as bark method.

Multilevel Inheritance In Java

In multi-level inheritance, we have a chain of inheritance. This means that we have a parent class that is inherited by a derived class. Derived class in turn acts as a parent to another class and so on.

The multi-level inheritance can be represented as below:

multilevel inheritance

As seen in the above figure there is a parent class A. Class B inherits from Class A. Then there is another class C that in turn inherits from Class B. Thus we can see that it forms a chain of inheritance. Here class B becomes an intermediary class that connects classes A and C.

Continuing with our Animal class example below, we can have a Dog class derived from Animal class. Then we can have another class Puppy which is a baby dog derived from Dog class. This way, we can have the multilevel inheritance.

An example program for Multilevel Inheritance is shown below.

import java.util.*; 
import java.lang.*; 
import java.io.*; 
//parent class A  
class A 
{ 
    public void print_A() 
    { 
        System.out.print("SoftwareTestingHelp "); 
    } 
} 
//Derived class B - intermediary  
class B extends A 
{ 
    public void print_B() 
    { 
        System.out.print("Java Series "); 
    } 
} 
//Derived Class C  
class C extends B 
{ 
    public void print_C() 
    { 
        System.out.print("Tutorials"); 
    } 
} 

public class Main 
{ 
    public static void main(String[] args) 
    { 
        C c_obj = new C();  //create Class C obj 
        c_obj.print_A();    //call grandparent class method
        c_obj.print_B();    //call parent class method
        c_obj.print_C();    //call member method
    } 
}

Output:

Multilevel inheritance

We have programmed the exact chain shown above. Then in the main method, we create an object of class C. The class C object then can access the methods of its parent B as well as grandparent A.

Hierarchical Inheritance In Java

A class can have more than one class derived from it. So we have one base or superclass and more than one subclasses. This type of inheritance is called “Hierarchical inheritance”.

The hierarchical inheritance is diagrammatically represented below:

Hierarchical inheritance in Java

As an example of hierarchical inheritance, we can represent Animal class as a superclass and then have more than one animal like Cat, Dog, Cow, etc. derived from it.

The Java program below demonstrates the Hierarchical Inheritance in Java.

//class Parent 
class Parent 
{ 
    public void print_parent() 
    { 
        System.out.println("In ::Parent class"); 
    } 
} 
//child1 class  
class Child1 extends  Parent
{ 
    public void print_child1() 
    { 
        System.out.println("In ::Child1 class"); 
    } 
} 
//child2 class  
class Child2 extends Parent 
{ 
    public void print_child2() 
    { 
        System.out.println("In ::Child2 class"); 
    } 
} 
//child3 class
class Child3 extends Parent 
{ 
    public void print_child3() 
    { 
        System.out.println("In ::Child3 class"); 
    } 
} 
  
public class Main 
{ 
    public static void main(String[] args) 
    { 
        Child1 ch1 = new Child1();      //create a Child1 class object
        ch1.print_child1();             //call its member method
        Child2 ch2 = new Child2();      //create a Child2 class object
        ch2.print_child2();             //call its member method
        Child3 ch3 = new Child3();      //create a Child3 class object
        ch3.print_child3();             //call its member method
        ch3.print_parent();             //call parent class method with any object
    } 
}

Output:

hierarchical example output

As we see from the program we have a parent class and three child classes derived from this parent. In the main method, we create an object of each of the child classes and call their respective member methods.

For calling the methods of the parent class, note that we can use any of the child class objects as all have access to the parent class.

Multiple Inheritance In Java

Multiple inheritance is a situation in which one class can inherit from more than one class i.e. one class can have more than one parent. By doing this, the class can have more than one superclass and thus acquire the properties and behavior of all its superclasses.

The diagrammatic representation of Multiple Inheritance is shown below:

Multiple inheritance in Java

As shown above, we can derive a class from more than one class simultaneously. This way the derived class will acquire the features of all of its parent classes. This may give rise to serious ambiguities especially when the features inherited are the same.

Note: Java does not support multiple inheritance using classes. But it supports multiple inheritance using interfaces which we will discuss in our next tutorial on inheritance.

Since Java does not support multiple inheritance with classes, we will not go into the details. However, later in the tutorial, we will try to understand the reasons behind Java not supporting multiple inheritance.

Hybrid Inheritance In Java

Hybrid inheritance is a combination of one or more types of inheritances that we have discussed above. Any combination however results in a type of multiple inheritance that is not supported by Java.

A hybrid inheritance can be diagrammatically represented as below.

Hybrid Inheritance in Java

Hence Java does not support hybrid inheritance as well with classes. But like multiple inheritance, we can implement hybrid inheritance in Java using interfaces. We will discuss this in detail in our next tutorial.

Why Java Doesn’t Support Multiple Inheritance?

Java aims at simplicity in programs. This applies even to OOP features. So when it comes to multiple inheritance, some ambiguous situations may arise when we derive a class from more than one class.

Now let’s understand the problems that may arise when we have multiple inheritance in our program.

Consider the following Multiple Inheritance systems.

multiple inheritance systems

If we see the above system, it is self-explanatory. Here class A and class B are two-parent classes inherited by class C. Now we have shown that both the classes A and B have a method with the same name i.e. print (). So when class C inherits A and B, then it will get both the versions of the print () method.

In this case, class C will not know which method it should inherit. This is the ambiguous situation we mentioned above that arises in the case of multiple inheritance.

Hence, Java issues a compiler error when the class inherits from more than one class.

The following Java program will demonstrate this.

class A{
    void print(){
        System.out.println("Class A :: print()");
    }
}

class B{
    void print(){
        System.out.println("Class B :: print()");
    }
}
class C extends A , B{      //let C inherit from A and B
}
public class Main
{
	public static void main(String[] args) {
	 C cObj = new C();
	 c.print();
	}
}

Output:

a compiler error

As seen from the output, the Java compiler issues an error when it finds that the class extends two classes.

Although Java does not allow two classes to be inherited simultaneously, it does offer us a way around this limitation. We can simulate multiple inheritance using interfaces instead of classes. We will discuss this in our subsequent tutorials.

Diamond Problem

Multiple inheritance results in a situation called “Diamond problem”.

Consider that we have the following inheritance system.

class Super{

 void show(){}

}	
class Sub1 extends super{

void show1(){}

}

class Sub2 extends super{

void show2(){}

}

class sample extends Sub1,Sub2{

	//Sample class code here
}

We can represent this system diagrammatically as shown below:

Diamond Problem

As we can see from the above diagram, the entire inheritance system appears in a diamond shape. Because of this diamond structure, the ambiguity is named the “Diamond Problem”.

As explained earlier for multiple inheritance, the ambiguity here is the multiple number of copies of the show () method that the Sample class obtains as a result of inheritance. As there are multiple paths it achieves the show () method and there is an ambiguity regarding which copy to inherit.

As with multiple inheritance, the diamond problem can also be resolved using interfaces.

Inheritance Rules In Java

Till now we have seen the basics of inheritance as well as the types of inheritance in Java, let’s list some rules that we need to follow while developing applications with inheritance.

Rule#1: Java does not support Multiple Inheritance

As we have already seen, Java does not support multiple inheritance in any form. When multiple inheritance is attempted in a program, the Java compiler issues compiler error.

Rule#2: Java does not permit Cyclic Inheritance

A class inheriting itself to form a cycle is called Cyclic Inheritance.

Consider the following classes, class1 and class2.

class class1 extends class 2{}

class class2 extends class 1{}

The above situation forms a loop. This is not permitted in Java.

Rule#3: We cannot inherit private data members

We have already learned in the “Access modifiers” topic that members with private access cannot be inherited.

Rule#4: Constructors are not inherited

As constructors are used for creating class objects, they are not inherited from one class to another.

Rule#5: We can use parent reference to access child objects

We have already seen various examples of inheritance. We can create a reference of type parent class and then assign it a derived class object created using the new keyword.

If super is a superclass and sub is class derived from super as shown below.

class super{}
class sub extends super{
	public static void main(String[] args){
		super s_obj = new sub();
	}
}

Rule#6: Parent constructors are executed because of super () in derived constructors

One of the rules state that constructors cannot be inherited. But the constructor of the superclass can be executed inside the constructor of the derived class using super () call.

Frequently Asked Questions

Q #1) Which type of inheritance is not supported by Java?

Answer: Java does not support multiple inheritance as it can give rise to problems in applications like the diamond problem. Java also does not support hybrid inheritance as it is a combination of one or more inheritance types and can ultimately turn into multiple inheritance.

Q #2) Which of the members of the class can be inherited?

Answer: A class can inherit public and protected members of its base class but cannot access the private members of the base class.

Q #3) Why is Multiple Inheritance not allowed?

Answer: Multiple inheritance results in ambiguity when two-parent classes have methods with the same prototype. In this case, the derived class faces an ambiguity regarding from which base class should it inherit the method.

Multiple inheritance may also result in a diamond problem in Java. Hence Java does not support multiple inheritance.

Q #4) Why do you need Multiple Inheritance?

Answer: Languages like Java and C# enforce the multiple inheritance using multiple interfaces. So when we need to inherit features from more than one interface, then we need multiple inheritance.

Q #5) What is the major use of Multilevel Inheritance?

Answer: A class derived from another class which in turn is derived from a third class is said to exhibit multilevel inheritance. The levels in this type of inheritance can be extended to any number as long it maintains clarity and simplicity.

We can depict different levels of species using multilevel inheritance. From the programming point of view, when we want to represent various levels of application classes, then we go for multilevel inheritance.

Conclusion

In this tutorial, we have discussed the types of inheritance in Java. Java supports only Single, Multilevel, and Hierarchical types of inheritance. Java does not support Multiple and Hybrid inheritance. We have discussed the Multiple inheritance ambiguity and Diamond problem in Java.

Then we discussed the various rules that we should follow while implementing inheritance in Java. With this, we have completed our discussion on the IS-A relationship in Java.

=> Watch Out The Simple Java Training Series Here.