Let’s understand,
Start with a Basic BankAccount
class BankAccount:
def withdraw(self, amount):
print(f"Withdrew {amount}")
Now every account will have its own rules for withdrawing
So subclasses will override this method
1. Overriding → same method, redefined in child class
-
Happens in Inheritance
-
The parent class has a method
-
Child class gives its own version of that method
class SavingsAccount(BankAccount):
def withdraw(self, amount):
print(f"SavingsAccount: Withdrew {amount} after checking balance")
class CurrentAccount(BankAccount):
def withdraw(self, amount):
print(f"CurrentAccount: Withdrew {amount} with overdraft support")
Now when you use it:
acc1 = SavingsAccount()
acc2 = CurrentAccount()
acc1.withdraw(100) # Outputs: SavingsAccount: Withdrew 100 after checking balance
acc2.withdraw(200) # Outputs: CurrentAccount: Withdrew 200 with overdraft support
This is → Method Overriding
Same method name → but each child writes their own logic
Used in → Runtime Polymorphism
2. Overloading → same method name, but different number/type of arguments
But wait…
Python does NOT support method overloading directly like Java or C++
But we can adjust using default values or *args
Deposit with Flexible Options
class BankAccount:
def deposit(self, amount, source="cash"):
print(f"Deposited {amount} via {source}")
Now:
acc = BankAccount()
acc.deposit(100) # Deposited 100 via cash
acc.deposit(200, "cheque") # Deposited 200 via cheque
acc.deposit(300, "online") # Deposited 300 via online
Same method → different arguments
This is → Method Overloading (Python style)
Used in → Compile-Time Polymorphism (simulated in Python)
Summary
Feature | Overriding | Overloading |
|---|---|---|
Definition | Child class gives its own version | Same method name, different inputs |
Used In | Inheritance (Parent → Child) | Same class mostly |
Python Support | ✔ Yes | ⚠ Not native, workaround via args |
Type | Runtime Polymorphism | Compile-time Polymorphism (simulated) |