Python Program: Inheritance and
Method Overriding
1. Introduction to Inheritance
Inheritance is one of the core concepts of Object-Oriented Programming (OOP). It allows
a class (called a child or derived class) to inherit the attributes and methods of another
class (called a parent or base class). This promotes code reusability and hierarchical
classification.
Types of Inheritance in Python:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
2. What is Method Overriding?
Method Overriding occurs when a child class provides a specific implementation of a
method that is already defined in its parent class. The method in the child class overrides
the method in the parent class.
3. Python Program to Demonstrate Inheritance and Method Overriding
class Animal:
def sound(self):
print("Animals make sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
class Cat(Animal):
def sound(self):
print("Cat meows")
# Creating objects
animal = Animal()
dog = Dog()
cat = Cat()
# Calling methods
animal.sound()
dog.sound()
cat.sound()
4. Output of the Program
Animals make sound
Dog barks
Cat meows
5. Explanation of the Code
- `Animal` is the base class that has a method `sound()`.
- `Dog` and `Cat` are derived classes inheriting from `Animal`.
- Both `Dog` and `Cat` override the `sound()` method to provide their own
implementation.
- When calling `sound()` using the child class objects, the overridden version of the
method is executed.
6. Benefits of Inheritance and Method Overriding
1. Code Reusability – Base class features can be reused.
2. Polymorphism – Allows the same method name to behave differently depending on the
object.
3. Extensibility – New features can be added to existing code easily.
4. Simplified Code – Easier to manage and update code.
7. Real-Life Example of Inheritance
Think of a general class ‘Vehicle’ with a method `start()`. Now a child class like ‘Car’ or
‘Bike’ can inherit from `Vehicle` and override `start()` to provide their specific behavior
like `Car starts with a key` or `Bike starts with a button`. This makes the design clean and
realistic.
8. Conclusion
Inheritance and Method Overriding are powerful features in Python. They enable us to
build flexible and reusable code structures. Understanding how these concepts work helps
in writing better and modular programs that reflect real-world systems accurately.