Inheritance in Object-
Oriented Programming
(OOP)
Inheritance in Object-Oriented Programming (OOP) is a mechanism
that enables one class to inherit the attributes and behaviors
(fields and methods) of another class. This facilitates code reuse,
allowing a new class to be derived from an existing class and either
extend or alter its behavior.
How Inheritance Works
Here’s how it works:
1 2
Parent (Base) Class Child (Derived) Class
The class from which properties and methods are The class that derives properties and methods from
inherited by another class. It is also referred to as the parent class. It is also known as the subclass.
the superclass.
Types of Inheritance: Single Inheritance
A class inherits from a single parent class.
Types of Inheritance: Multiple Inheritance
A class inherits from more than one parent class. (Note:
Not all programming languages support this directly;
for instance, Java does not allow multiple inheritance of
classes, while Python does.)
Types of Inheritance: Multilevel and Hierarchical Inherita
Multilevel Inheritance Hierarchical Inheritance
A class inherits from a child class, forming a chain of inheritance. Several classes inherit from one parent class.
Types of Inheritance: Hybrid Inheritance
A combination of two or more types of inheritance.
Important Features of Inheritance
Code Reusability Overriding
The child class inherits methods and properties A subclass can implement its own version of
from the parent class, eliminating the need to methods defined in the parent class. This process is
duplicate existing code. known as method overriding.
Accessing Parent Methods/Properties Extending Functionality
By using super(), a subclass can invoke methods or A child class can enhance or extend the
access properties from the parent class. functionality of the parent class without modifying
the parent class itself.
Example of Method
Overriding
In the example above, both Dog and Cat override the speak()
method. If we had not overridden the method, both would invoke
the speak() method from the Animal class, which outputs "makes a
sound."
Advantages of Inheritance
Code Organization Easier Maintenance
Structuring code into parent and child classes If there
simplifies maintenance and management.