Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Method Overloading and Method Overriding

Method Overloading and Method Overriding

Method Overloading means defining multiple methods in the same class with the same name but different parameters (number or type).

Note: Python does not support true method overloading like Java or C++. Instead, it can be simulated using default arguments or *args.

Why it’s useful:

  • Allows function flexibility with different numbers of arguments.
  • Makes the interface simpler for users.

Example:

class Calculator:
    def add(self, a=0, b=0, c=0):
        return a + b + c

calc = Calculator()
print(calc.add(2))           # 2
print(calc.add(2, 3))        # 5
print(calc.add(2, 3, 4))     # 9

Method Overriding occurs when a child class defines a method with the same name and parameters as a method in its parent class, effectively replacing the parent’s implementation.

  • It is a core concept of inheritance.

Example:

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

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

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

How can we help?

Leave a Reply

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