What is polymorphism?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Polymorphism, a fundamental concept in computer science, particularly in object-oriented programming, refers to the ability of different objects to respond in their own way to the same message or method call. It comes from Greek words meaning "many forms." Let's break it down with an example:

Basic Concept:

  • Polymorphism allows objects of different classes to be treated as objects of a common superclass. The specific form of the behavior (method implementation) is determined by the actual class of the object.

Types of Polymorphism:

  1. Compile-Time Polymorphism (Method Overloading):

    • Same method name but different parameters within the same class.
    • The compiler determines which method to call at compile time based on the method signature.
  2. Runtime Polymorphism (Method Overriding):

    • Derived classes have a method with the same name as a method in the base class.
    • The specific method that gets called is determined at runtime, based on the object's class.

Example of Polymorphism:

Consider a simple example with a base class Animal and derived classes Dog and Cat:

class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def speak(self): print("Bark") class Cat(Animal): def speak(self): print("Meow") # Polymorphism in action def animal_sound(animal): animal.speak() # Creating instances my_dog = Dog() my_cat = Cat() # Calling the function with different objects animal_sound(my_dog) # Outputs: Bark animal_sound(my_cat) # Outputs: Meow

In this example:

  • The Animal class has a method speak().
  • Both Dog and Cat classes override the speak() method.
  • The animal_sound function demonstrates polymorphism. It can take any Animal type and call its speak method. At runtime, Python figures out whether it's a Dog or Cat instance and calls the appropriate speak method.

Significance in Programming:

  • Flexibility: Polymorphism allows for flexible and reusable code. You can write code that works on the superclass type, but it will work with any subclass type.
  • Maintainability: It makes maintaining and expanding the code easier, as changes in the superclass automatically propagate to subclasses (if the method isn't overridden).
  • Extensibility: New classes can be introduced that inherit from the superclass without changing the function that utilizes polymorphism.

Polymorphism is a cornerstone of object-oriented programming, enabling objects of different classes to be treated uniformly while still maintaining their distinct behaviors.

TAGS
Object-Oriented Programming
CONTRIBUTOR
Design Gurus Team
Explore Answers
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Image
Grokking Data Structures & Algorithms for Coding Interviews
Image
Grokking 75: Top Coding Interview Questions