Site icon Care All Solutions

Polymorphism

Polymorphism is a core principle of object-oriented programming (OOP) that allows objects of different types to be treated as if they were of the same type. It enables flexibility and extensibility in code.

Types of Polymorphism

  1. Method Overloading: This occurs when multiple methods in the same class have the same name but different parameters. The compiler determines which method to call based on the arguments passed.  

Python

class Shape:
    def area(self, length, breadth):
        return length * breadth

    def area(self, radius):
        return 3.14 * radius * radius
  1. Method Overriding: This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

Python

class Animal:
    def make_sound(self):
        print("Animal is making a sound")

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

Example:

Python

class Shape:
    def area(self):
        pass  # Abstract method

class Rectangle(Shape):
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def area(self):
        return self.length * self.breadth 

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

# Create objects
rect = Rectangle(5, 4)
circle = Circle(3)

# Using polymorphism
shapes = [rect, circle]
for shape in shapes:
    print(shape.area())

Key Points

By understanding polymorphism, you can write more flexible and adaptable object-oriented code.

Why is polymorphism important?

It enhances code flexibility, reusability, and maintainability.

What are the types of polymorphism?

Method overloading and method overriding.

What is method overloading?

Having multiple methods with the same name but different parameters within a class.

What is method overriding?

Redefining a method in a subclass with the same name and parameters as the parent class.

Which type of polymorphism is more common?

Method overriding is more commonly used than method overloading.

Can you give a real-world example of polymorphism?

Different shapes (circles, squares, triangles) can be treated as shapes and have an area method.

How is polymorphism used in everyday programming?

In collections, polymorphism allows you to treat different object types uniformly.

When should I use polymorphism?

When you need to perform similar actions on different objects.

How can I avoid potential issues with polymorphism?

Carefully consider the base class interface and ensure subclasses adhere to it.

Read More..

Exit mobile version