Method Overriding

Method Overriding is a feature of Inheritance in Object-Oriented Programming (OOP).

It allows a child class to provide a specific implementation of a method that is already defined in its parent class.

In simple words:
The child class changes the behavior of a parent class method.

Why Use Method Overriding?

  • To modify or extend parent behavior
  • To implement runtime polymorphism
  • To customize functionality in child classes

Basic Example

class Animal:
def sound(self):
print("Animal makes a sound")class Dog(Animal):
def sound(self):
print("Dog barks")d = Dog()
d.sound()

Output:

Dog barks

Here:

  • Dog inherits from Animal
  • The sound() method in Dog overrides the parent method
  • The child version runs instead of the parent version

Using super() in Method Overriding

Sometimes we want to use the parent method along with the child method.

class Animal:
def sound(self):
print("Animal makes a sound")class Dog(Animal):
def sound(self):
super().sound()
print("Dog barks")d = Dog()
d.sound()

Output:

Animal makes a sound
Dog barks

super() calls the parent class method.

Rules of Method Overriding

  • Method name must be the same
  • Parameters should be the same
  • Must use inheritance
  • Happens at runtime

Example with Constructor Overriding

class Person:
def __init__(self):
print("Person Constructor")class Student(Person):
def __init__(self):
print("Student Constructor")s = Student()

Output:

Student Constructor

The child constructor overrides the parent constructor.

To call parent constructor:

class Student(Person):
def __init__(self):
super().__init__()
print("Student Constructor")

Method Overriding vs Method Overloading

Method Overriding
Same method name
Same parameters
Different implementation in child class
Requires inheritance

Method Overloading
Same method name
Different parameters
Python supports it using default arguments

Key Takeaway

Method Overriding allows a child class to redefine a parent class method.

It supports runtime polymorphism and makes OOP programs flexible and extensible.

Home » OBJECT ORIENTED PROGRAMMING IN PYTHON (OOP) > OOP Concepts > Method Overriding