Feature | Method Overloading | Method Overriding |
---|---|---|
Concept | Same method name, different parameters | Redefining a parent class method in a subclass |
Defined In | Same class | Child class (inherits from parent class) |
Python Support | Not true overloading (handled manually) | Fully supported |
Think of a calculator app where the add() button works for:
- 2 numbers β
add(2, 3)
- 3 numbers β
add(2, 3, 4)
- Strings β
add("Hello", "World")
The function name is the same (add
), but it behaves differently depending on the arguments.
Think of a base class Vehicle with a method start_engine().
A Car overrides it to start with a key, while a Bike overrides it to start with a kick.
The method name is the same, but the subclass provides its own version.
Python doesnβt support traditional method overloading like Java or C++, but we can simulate it using default arguments or *args
.
args
class Calculator:
def add(self, *args):
return sum(args)
calc = Calculator()
print(calc.add(2, 3)) # 5
print(calc.add(2, 3, 4)) # 9
print(calc.add()) # 0
class Greeting:
def say_hello(self, name=None):
if name:
print(f"Hello, {name}!")
else:
print("Hello, there!")
greet = Greeting()
greet.say_hello() # Hello, there!
greet.say_hello("Alice") # Hello, Alice!