close menu
Polymorphism--Method-overloading-and-overriding-in-python Polymorphism Method overloading and overriding in python

Polymorphism Method overloading and overriding in python

18 February 2025

 Polymorphism  Method overloading and overriding in python


 Polymorphism: Method overloading and overriding

**Polymorphism
Polymorphism allows a single internface to be used for diffrent data types, enabling code flexility and reusability. It is primaryly implemented in two ways:

**Method Overloading (Compile-time-Polymorphism)
•Allows multiple methods in the same class to have same name but diffrent parameters(number, type or both).
•The method to be executed is determined at compile time.

Example:
class MathOperations {
   int add(int a, int b) {
       return a + b;
   }
   double add(double a, double b) {
       return a + b;
   }
}

**Method Overriding (Runtime Polymorphism)
•Occurs when a child class provides a specific implementation of a method that is already defined in its parent class.
•The overrdden method in the child class must have the same name, return type and parameters.
•The method to be executed is determined at runtime.

Example:
class Animal {
   void makeSound() {
       System.out.println("Animal makes a sound");
   }
}
class Dog extends Animal {
   @Override
   void makeSound() {
       System.out.println("Dog barks");
   }
}

Polymorphism enhances code flexibility by allowing methods to process different data types and enabling dynamic method behavior in inherited classes.

Whatsapp logo