Understanding Inheritance in OOP
What is Inheritance?
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (subclass/child) to reuse and extend the attributes and methods of another class (superclass/parent).
It promotes code reusability, reduces duplication, and establishes a hierarchical relationship between classes.Note
Inheritance enables a hierarchical relationship between classes, promoting code reusability and reducing redundancy.
How Inheritance Works
- Superclass (Parent Class):
- Defines shared attributes and methods.
- Example: Vehicle has attributes like speed, capacity, and methods like move().
- Subclass (Child Class):
- Inherits attributes and methods from the parent.
- Can add its own specialized features.
- Example: Car adds numberOfDoors; Aeroplane adds fly().
- Consider a Vehicle superclass with attributes like fuelType and capacity.
- Subclasses like Car and Aeroplane inherit these attributes and add their own, such as electric for Car or commercial for Aeroplane.
Benefits of Inheritance
- Single Inheritance: One parent → one child.
- Multilevel Inheritance: A child acts as a parent for another child (e.g., Vehicle → Car → ElectricCar).
- Hierarchical Inheritance: Multiple children share the same parent.
- Multiple Inheritance: Supported in Python (via multiple parent classes) but not directly in Java (handled using interfaces).
When designing a class hierarchy, focus on identifying common attributes and behaviors that can be abstracted into a superclass.
Access Modifiers and Inheritance
- Public: Accessible everywhere.
- Protected: Accessible within the package (Java) or subclass (Java/Python).
- Private: Not inherited; accessible only inside the parent class.
- Default (Java): Package-level access.