Skip to content
C

Types of Inheritance

Inheritance can be organized in different patterns: single (one child, one parent), multilevel (a chain of inheritance across generations), and hierarchical (multiple children inheriting from one common parent).


1. What are the Types of Inheritance?

Inheritance can be organized in different patterns: single (one child, one parent), multilevel (a chain of inheritance across generations), and hierarchical (multiple children inheriting from one common parent). Java does not support multiple inheritance of classes directly (a class extending two classes at once).

2. Why is it used?

Understanding these patterns helps you design class relationships correctly, based on how features are genuinely shared between different real-world categories of objects.

3. Real-Life Example

Single inheritance is like a child inheriting from one parent. Multilevel is like traits passing from grandparent to parent to child. Hierarchical is like multiple siblings all inheriting common family traits from the same parent.

4. Syntax

java
// Single class B extends A { } // Multilevel class C extends B { } // where B extends A // Hierarchical class D extends A { } class E extends A { }

5. Example Program

java
class Animal { void eat() { System.out.println("This animal eats food"); } } class Dog extends Animal { } // hierarchical: sibling 1 class Cat extends Animal { } // hierarchical: sibling 2 public class InheritanceTypesDemo { public static void main(String[] args) { Dog d = new Dog(); Cat c = new Cat(); d.eat(); c.eat(); } }

Output:

This animal eats food
This animal eats food

7. Key Points to Remember

  • Java avoids multiple inheritance of classes to prevent ambiguity (known as the "Diamond Problem").
  • Multiple inheritance of behaviour is instead achieved in Java through interfaces (covered later).
  • Hierarchical inheritance is common when several distinct classes share the same base features.