What are the Types of Inheritance in Java? Examples and
Tips to Master Inheritance

Table of Contents

What are the Types of Inheritance in Java? Examples and Tips to Master Inheritance

Inheritance in OOP (Object Oriented programming), Java is a mechanism that allows the creation of a new class by reusing an existing class. For example, you can create a class, ‘Rose,’ based upon an existing class, ‘Flower.’ So, in the ‘Rose’ class, you can add

like color and scent that can be derived from the ‘Flower’ class. As a result, it will help you save time and effort without having to write the same code several times. 

Now, there are different types of inheritance in Java that incorporate unique concepts. However, the core concept remains the same. That is the parent and child class links in such a way that they pass the methods through different generations or child classes. 

In this article, you will learn each of the types of inheritance in Java in detail and know how to master them. 

5 major types of inheritance in Java

*medium.com

Inheritance and its Types in Java

Inheritance in Java is the technique through which an object gets all the behaviors and properties of its parent object. As a result, you can build a new class based on an existing class. The new class is known as the child or sub-class, whereas the existing class is known as the parent or superclass. The child class can access and reuse all the members, including methods and fields of the parent class. The inheritance represents the ‘is-a’ relationship that indicates the parent-child relationship. 

Here, you will learn about the five types of inheritance in Java and their examples.

Single Inheritance in Java

Single inheritance is one of the basic types of inheritance in Java that requires one parent class and one child class. Through this inheritance, you can extend one class from another by reusing the methods and fields of the parent class. It makes your code much easier to understand and helps update it.

For example, let your Animal class hold the attribute like eating fish. Now, a new class named Cat automatically receives this attribute using the single inheritance mechanism. This way, the child class Cat carries the attributes of the parent class Animal without the requirement of complex maintenance procedures. 

Also, the Cat class has its own attribute, meow that is not inherited from the parent class. 

Single inheritance in Java

*softwaretestinghelp.com

				
					class Animal{  
void eat(){System.out.println("Eating");}  
}  
class Cat extends Animal{  
void meow(){System.out.println("Meowing");}  
}  
public class Main{  
public static void main(String args[]){  
Cat c=new Cat();  
c.meow();  
c.eat();  
}}  

				
			

Output:

Meowing

Eating

Multilevel Inheritance in Java

Another crucial approach from the five types of inheritance in Java is the multilevel inheritance. In this case, first, you need to inherit a child class from a parent class. Again, you should inherit another class from that child class. As a result, all the attributes will pass from the parent class to the lowest level of the sub-classes. This technique helps you to extend the parent class with a step-by-step approach. 

Multilevel inheritance in Java

*naukri.com

Now, you can take an example where the parent class is Bird, and the child class is Parrot. Now, you can extend the Parrot class again by creating a new class BabyParrot. So, the Parrot class extends the Bird class, and the BabyParrot class extends the Parrot class. So, changes in the topmost class Bird are automatically carried through the Parrot class and then by the BabyParrot class.

Coding:

				
					class Bird{  
void fly(){System.out.println("Flying");}  
}  
class Parrot extends Bird{  
void talk){System.out.println("Talking");}  
}  
class BabyParrot extends Parrot{  
void eat(){System.out.println("Eating");}  
}  
public class Main{  
public static void main(String args[]){  
BabyParrot p=new BabyParrot p();  
p.eat();  
p.talk();  
p.fly();
}}  

				
			

Output:

Eating

Talking

Flying

Hierarchical Inheritance in Java

For this inheritance concept, one parent class has multiple child classes. Every child class obtains the methods from the parent class, and they have their own unique features. This is one of the best types of inheritance in Java that keeps your code organized, specifically when the parent class encapsulates the behaviors that the child classes acquire from it.

Here, you will get an example of an Instrument class that has the attribute type. Now each of its child (Flute, Violin, and Trumpet) get the type attribute through the showType() method. They also have unique attributes, such as playing flute, violin, and trumpet. So, let’s see the coding part –

Coding:

				
					class Instrument {
    String type = "String Instrument";

    void showType() {
System.out.println("Instrument type: " + type);
    }
}

class Flute extends Instrument {
    void playFlute() {
System.out.println("Playing flute scales.");
    }
}

class Violin extends Instrument {
    void playViolin() {
System.out.println("Playing violin harmonies.");
    }
}
class Trumpet extends Instrument {
    void playTrumpet() {
System.out.println("Playing trumpet melodies.");
    }
}

public class Main {
    public static void main(String[] args) {
        Flute flt = new Flute();
flt.showType();     // Inherited from Instrument
flt.playFlute();   // Unique to Flute

        Violin vio = new Violin();
vio.showType();     // Inherited from Instrument
vio.playViolin();    // Unique to Violin

      Trumpet tpt = new Trumpet();
tpt.showType();     // Inherited from Instrument
tpt.playViolin();    // Unique to Trumpet
    }
}

				
			

Output:

Instrument type: String Instrument

Playing flute scales.

Instrument type: String Instrument

Playing violin harmonies.

Instrument type: String Instrument

Playing trumpet melodies.

Hybrid Inheritance in Java

Hybrid inheritance refers to multiple types of inheritance in Java in a single program. As Java doesn’t support multiple class-based inheritance, you can create hybrid types using class hierarchies and interfaces. 

Here, you will learn hybrid inheritance, which is a combination of single and multiple inheritance using interfaces. So, we have created a parent class named Cat. This Cat class has two interfaces – MotherCat and FatherCat. The Kitten class extends both the MotherCat and FatherCat classes. So, it’s an example of multiple inheritance via interface. The Kitten class inherits the show() method from its parents, MotherCat and FatherCat. The Kitten class also extends the Cat class, which refers to single inheritance. So, this inheritance covers various inheritance in Java types

				
					class Cat
{  
public void displayCat()  
{  
System.out.println("Two Cats");  
}  
}  
interface MotherCat
{  
public void show();  
}  
interface FatherCat
{  
public void show();  
}   
public class Kitten extends Cats implements MotherCat, FatherCat
{  
public void show()  
{  
System.out.println("MotherCat and FatherCat are Cats ");  
}    
public void displayKitten()  
{  
System.out.println("MotherCat and FatherCat have one Kitten");  
}   
public static void main(String args[])  
{  
Kitten kit = new Kitten();  
System.out.println("Hybrid Inheritance in Java");  
kit.show();  
kit.displayKitten();  
}  
}      

				
			

Output:

Hybrid Inheritance in Java

MotherCat and FatherCat are Cats

MotherCat and FatherCat have one Kitten

Multiple Inheritance in Java

Multiple inheritance indicates a situation where a single class tries to derive its features from multiple parent classes. Thus, it leads to confusion between classes about the methods with the same names. So, Java doesn’t support this inheritance type directly. However, unlike other types of inheritance in Java, you can achieve it through interfaces. 

Here are the two interfaces, Student 1 and Student. Both of them contain methods of the same signature. As these methods are abstract in nature, there is no conflict in the code. The Test class implements both these interfaces, including the implementation of the learn(). The implementation is executed by calling the t.learn() method

Coding:

				
					/ Interface 1
interface Student1 {
    void learn();
}

// Interface 2
interface Student2 {
    void learn();
}

// Class implementing both interfaces
class Test implements  Student1,  Student2 {

    // Overriding learn() method from both interfaces
    public void learn() {
System.out.println("Book Class");
    }

    // Main driver method
    public static void main(String args[]) {
        Test t = new Test();
t.learn();
    }
}


				
			

Output:

Book Class

Benefits of Different Types of Inheritance in Java

You can gain these facilities by implementing different types of inheritance in Java –

    • Code reusability: The first and foremost benefit you can gain is code reusability. The inheritance mechanism helps you avoid code redundancy. 
    • Flexibility: Types of inheritance in Java employ structural and hierarchical ways to organize your code. As a result, your code looks clean and easily represents the relationship between different classes.
    • Easy to maintain: The subclasses achieve the features of the superclass by inheritance. Thus, if you change the superclass, the subclasses will also reflect those changes. This makes your code easier to maintain. 
    • Simplified design: As you can extend the classes with the types of inheritance in Java, you don’t need to write the code from scratch. So, it helps to avoid unnecessary complications. 

Conclusion

You can acquire advanced programming knowledge by understanding the concept of numerous types of inheritance in Java. It supports levelling up your skills and remains competitive in the job market. Self-learning and practicing are great strategies for boosting your expertise in the types of inheritance in Java.

However, you should opt for professional computer science courses like the Executive Programme in full stack web development to drive your career on the right path. This course will provide you with more exposure to real-world applications through which you can understand the concepts of inheritance better!

Frequently Asked Questions

Why do you need different types of inheritance in Java?

Inheritance establishes strong hierarchical relationships between different classes and promotes code reusability and maintenance. Hence, the new classes automatically achieve the behaviors and properties of the superclasses.

What are the types of inheritance in Java?

There are four types of inheritance in Java. These are single, multilevel, hierarchical, and hybrid inheritance. It is to be noted that Java doesn’t support multiple inheritance. But you can create it with the help of interfaces.

What is the diamond problem?

The diamond problem refers to the problem arising from multiple inheritance classes. That means there will be an ambiguity when a single class inherits from two or multiple classes. In this situation, the child class implements methods or attributes from multiple parents who might have the same name. As a result, the interpreter doesn’t understand which method/attribute should be considered.

What is the major difference between inheritance and polymorphism in Java?

Inheritance is applied to the classes, whereas polymorphism is applied to the methods. 

Enquiry

Fill The Form To Get More Information


Trending Blogs

Leave a Comment