Sobes.tech
Junior

What is polymorphism in programming?

sobes.tech AI

Answer from AI

Polymorphism (from Greek "many forms") is the ability of different objects to respond to the same message (method call) in different ways, depending on their type.

In object-oriented programming, polymorphism allows:

  • Working with objects of different classes through a common interface or base class.
  • Creating more flexible and extensible code.

Main types of polymorphism:

  • Compile-time (static) polymorphism: Implemented through method overloading. Methods with the same name but different signatures (number or types of parameters) are defined within a single class.
  • Run-time (dynamic) polymorphism: Implemented through method overriding. A method in a subclass has the same signature as a method in the parent class. The specific method to be called is determined at runtime depending on the actual type of the object.

Example in Python (dynamic polymorphism):

class Animal:
    def sound(self):
        pass # Base method, to be overridden

class Dog(Animal):
    def sound(self):
        # Override the sound method for Dog
        print("Woof")

class Cat(Animal):
    def sound(self):
        # Override the sound method for Cat
        print("Meow")

# Function working with objects through the base class Animal
def make_animal_sound(animal):
    animal.sound()

# Using polymorphism
dog = Dog()
cat = Cat()

make_animal_sound(dog) # Calls Dog.sound() -> Woof
make_animal_sound(cat) # Calls Cat.sound() -> Meow