What is Polymorphism ?

38
0

Polymorphism is a principle of object-oriented programming that allows you to use the same method name to perform different actions, depending on the context. This can help to reduce code duplication and make your code more flexible and reusable.

There are two main types of polymorphism in object-oriented programming:

  1. Method overriding: This occurs when a child class defines a method with the same name as a method in the parent class. When the method is called on an instance of the child class, it will execute the code in the child class’s method instead of the one in the parent class. This allows the child class to customize the behavior of the method to suit its needs.
  2. Method overloading: This occurs when a class defines multiple methods with the same name, but with different number or types of arguments. The correct method will be called based on the number and type of arguments passed to it.

Here is an example of polymorphism in Python using method overriding:

class Animal:
    def make_sound(self):
        return "Some generic animal sound"
    

class Dog(Animal):
    def make_sound(self):
        return "Bark"
    

class Cat(Animal):
    def make_sound(self):
        return "Meow"

In this example, the Animal class has a make_sound method that returns a generic animal sound. The Dog and Cat classes override this method and provide their own implementation that returns a specific sound for a dog or a cat.

Now, if you create an instance of the Animal class and call the make_sound method, it will return “Some generic animal sound”. But if you create an instance of the Dog class or the Cat class and call the make_sound method, it will return “Bark” or “Meow”, respectively.

Here is an example of polymorphism using method overloading:

class Calculator:
    def add(self, x, y):
        return x + y
    
    def add(self, x, y, z):
        return x + y + z

In this example, the Calculator class has two methods with the same name, add, but with different number of arguments. If you call the add method with two arguments, it will return the sum of those two arguments. If you call it with three arguments, it will return the sum of those three arguments.

This allows you to use the same method name, add, to perform different actions depending on the number of arguments passed to it.

Leave a Reply