Skip to main content
Practice

Adding Flexibility to Objects with Polymorphism

Polymorphism is one of the key concepts in object-oriented programming, allowing a method or class to perform in various ways.

By leveraging polymorphism, objects can operate differently through the same method or interface.


Understanding Polymorphism through Code

The following code defines the classes Animal, Dog, and Cat, and demonstrates polymorphism by implementing the speak method differently in each class.

Example of Using Polymorphism
class Animal:
def speak(self):
return "Makes a sound."

# Inherit from the Animal class
class Dog(Animal):
# Override the 'speak' method from Animal class
def speak(self):
return "Woof"

# Inherit from the Animal class
class Cat(Animal):
# Override the 'speak' method from Animal class
def speak(self):
return "Meow"

# Example usage of polymorphism
animal = Animal()
# 'Makes a sound.'
print(animal.speak())

dog = Dog()
# 'Woof'
print(dog.speak())

cat = Cat()
# 'Meow'
print(cat.speak())

In the code above, the speak method is defined differently in the Animal, Dog, and Cat classes.

Both the Dog and Cat classes inherit from the Animal class and override the speak method in their own way.

This phenomenon, where each object behaves differently for the same method call, is known as polymorphism.


What are the Advantages of Polymorphism?

In object-oriented programming, polymorphism offers the following benefits:

  • Increased Flexibility of Objects: You can handle various objects and data with a single interface (rules for interacting with objects).

  • Improved Code Reusability: Polymorphism improves code reusability, enhancing a program's scalability and maintainability.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.