Types of Inheritance in Java
🔷 What is Inheritance in Java?
Inheritance is the process by which one class (child) acquires the properties and behaviors (fields and methods) of another class (parent).
It promotes code reusability and is a key feature of object-oriented programming.
🔑 Syntax:
✅ Types of Inheritance in Java:
Type | Description |
---|---|
1. Single Inheritance | One class inherits from another. |
2. Multilevel Inheritance | A class inherits from a class which is already inherited from another class. |
3. Hierarchical Inheritance | Multiple classes inherit from a single parent class. |
4. Hybrid Inheritance | Combination of multiple types (achievable via interfaces in Java). |
❌ Note: Java does not support multiple inheritance with classes to avoid ambiguity (Diamond Problem). But it is allowed through interfaces.
🔹 1. Single Inheritance
A child class inherits directly from a parent class.
📌 Example:
🔹 2. Multilevel Inheritance
A class inherits from a class which itself inherits from another class.
📌 Example:
🔹 3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.
📌 Example:
🔹 4. Hybrid Inheritance (via Interfaces)
Java does not allow multiple inheritance with classes but allows it through interfaces, achieving hybrid inheritance.
📌 Example:
🚫 Why Java Does Not Support Multiple Inheritance with Classes?
To avoid ambiguity caused by the Diamond Problem.
🔻 Example of Diamond Problem (Not allowed in Java):
If both B
and C
inherit a method from A
, and D
inherits from both B
and C
, which method should D
use? To prevent this confusion, Java restricts multiple inheritance of classes, but allows it via interfaces.
🧠 Summary Table:
Type | Supports in Java | Example Components |
---|---|---|
Single Inheritance | ✅ Yes | One child, one parent |
Multilevel Inheritance | ✅ Yes | Grandparent → Parent → Child |
Hierarchical Inheritance | ✅ Yes | One parent, many children |
Multiple Inheritance | ❌ (with classes) ✅ (with interfaces) | Interfaces only |
Hybrid Inheritance | ✅ via interfaces | Mix of inheritance types |
Comments
Post a Comment