Inheritance in OOP
Inheritance in Object-Oriented Programming (OOP)
What is Inheritance?
Inheritance is a key principle of Object-Oriented Programming (OOP) that allows one class to inherit properties (attributes) and behaviors (methods) from another class. It establishes a relationship between parent (superclass/base class) and child (subclass/derived class) classes, enabling code reusability, hierarchy, and modular design.
1. Key Features of Inheritance
- Code Reusability: Avoids code duplication by allowing a subclass to reuse attributes and methods from its superclass.
- Extensibility: A child class can extend the functionality of the parent class by adding new methods or overriding existing ones.
- Hierarchy: Models real-world relationships by defining a structured class hierarchy.
- Method Overriding: The child class can redefine the parent’s method to provide a specific implementation.
- Access Control: Controls which attributes and methods are inherited using access modifiers (
private,protected,public).
2. Types of Inheritance
(A) Single Inheritance
A subclass inherits from only one superclass.
Example (Python)
(B) Multilevel Inheritance
A class inherits from another class, which itself is inherited by another class (forming a chain).
Example (Java)
(C) Multiple Inheritance (Supported in Python, Not in Java)
A subclass inherits from multiple parent classes. Java does not support multiple inheritance with classes but allows it with interfaces.
Example (Python)
(D) Hierarchical Inheritance
Multiple subclasses inherit from a single superclass.
Example (Java)
4. Access Modifiers and Inheritance
| Modifier | Same Class | Same Package | Subclass | Outside Package |
|---|---|---|---|---|
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default (no modifier) | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
5. super Keyword in Inheritance
superis used to refer to the parent class's methods and constructors.- It is often used when a subclass overrides a method but still needs the parent class’s functionality.
Example (Java)
Output:
6. Abstract Classes and Inheritance
An abstract class cannot be instantiated but can be inherited. It may contain abstract methods (without implementation).
Example (Java)
7. Interfaces and Inheritance (Java-Specific)
Java supports multiple inheritance through interfaces.
Example
8. Real-World Analogy of Inheritance
Imagine a Vehicle class that has properties like speed and fuelCapacity. Now, we create subclasses:
CarextendsVehicle→ InheritsspeedandfuelCapacity, addsnumDoors.BikeextendsVehicle→ InheritsspeedandfuelCapacity, addshasCarrier.
This demonstrates real-world hierarchical relationships.
Conclusion
- Inheritance allows a child class to reuse and extend the parent class.
- Different types: Single, Multilevel, Multiple, Hierarchical, Hybrid.
- Supports method overriding,
superkeyword, abstract classes, and interfaces. - Encourages code reusability and modular programming.
Comments
Post a Comment