DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-66 Types of Inheritance in Java

Inheritance is a powerful feature in Object-Oriented Programming (OOP) that allows a class to reuse the properties and methods of another class. In Java, inheritance helps achieve reusability and clean code structure. There are five types of inheritance.

1. Single Inheritance

One child class inherits from one parent class.

   Parent
     ↓
   Child
Enter fullscreen mode Exit fullscreen mode

2. Multilevel Inheritance

A class inherits from a class, which itself inherits from another class.

   GrandParent
        ↓
      Parent
        ↓
      Child
Enter fullscreen mode Exit fullscreen mode

3. Hierarchical Inheritance

Multiple classes inherit from the same parent class.

         Parent
         /   \
     Child1  Child2
Enter fullscreen mode Exit fullscreen mode

4. Hybrid Inheritance

Combines more than one type of inheritance (for example, multilevel + hierarchical).

       GrandParent
            ↓
         Parent
        /     \
   Child1    Child2
Enter fullscreen mode Exit fullscreen mode

Java does not support hybrid inheritance using classes directly, because it can lead to ambiguity and confusion in method resolution.

5. Multiple Inheritance

A class attempts to inherit from more than one parent class.

    Parent1   Parent2
        \     /
         Child
Enter fullscreen mode Exit fullscreen mode

Java does not support multiple inheritance with classes to avoid method conflict, commonly known as the Diamond Problem.

What is the Diamond Problem?

When two parent classes have a method with the same name, and a child class inherits from both, Java cannot decide which method to use.

       A
      / \
     B   C
      \ /
       D
Enter fullscreen mode Exit fullscreen mode

This is called the Diamond Problem. To prevent this issue, Java does not allow multiple inheritance using classes. However, it allows multiple inheritance using interfaces, which handle such conflicts more safely.

Top comments (0)