πΉ 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
Term | Meaning |
---|---|
Overriding | Child class redefines parent method |
Method Name | Must 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.