Method Overriding in Python | Easy Explanation with Examples



πŸ”Ή What is Method Overriding?

Method Overriding means:

A child class (subclass) writes its own version of a method that already exists in the parent class (superclass).

  • It helps the child class change or improve the behavior of a parent method.
  • The method name must be same in both classes.

πŸ”Έ Real-Life Example:

Imagine a general printer prints in black & white. But a color printer overrides that function and prints in color.


πŸ”Ή Basic Example of Method Overriding:

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):  # Overriding the parent's method
        print("Dog barks")

d = Dog()
d.speak()  # Output: Dog barks

βœ… Dog class has its own version of the speak() method.


πŸ”Ή Why Use Method Overriding?

βœ… To customize behavior
βœ… To add extra work in child class
βœ… To make code flexible and clean


πŸ”Ή Calling Parent Method Using super()

Sometimes we want to call the original (parent) method also:

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        super().speak()  # Call parent method
        print("Dog barks")

d = Dog()
d.speak()

🟒 Output:

Animal speaks
Dog barks


πŸ”Ή Another Example: Bank Account

class Account:
    def show_balance(self):
        print("Balance is $1000")

class SavingsAccount(Account):
    def show_balance(self):
        print("Savings balance is $1500")

a = SavingsAccount()
a.show_balance()


πŸ“ Practice Questions with Answers

❓ Q1: Create a class Shape with a method draw(). Override it in Circle and Square.

βœ… Answer:

class Shape:
    def draw(self):
        print("Drawing a shape")

class Circle(Shape):
    def draw(self):
        print("Drawing a circle")

class Square(Shape):
    def draw(self):
        print("Drawing a square")

c = Circle()
s = Square()

c.draw()
s.draw()


❓ Q2: Create a class Employee with method work(). Override it in Manager and Developer.

βœ… Answer:

class Employee:
    def work(self):
        print("Employee works")

class Manager(Employee):
    def work(self):
        print("Manager manages the team")

class Developer(Employee):
    def work(self):
        print("Developer writes code")

m = Manager()
d = Developer()

m.work()
d.work()


🧾 Summary

TermMeaning
OverridingChild class redefines parent method
Method NameMust be the same in both classes
Use of super()To call the parent class method from child

🎯 Quick Recap

  • Method Overriding = Changing a parent method in the child class.
  • Useful when child class needs a different behavior.
  • super() helps to use parent’s method with the new one.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *