202410151618 Status: #idea Tags: #object_oriented_programming #design_patterns #software_engineering #computer_science # Run-time polymorphism Run-time polymorphism describes a situation in which a method in a base class is overridden by a method in one or more derived classes. When you have objects from different derived classes treated as instances of the base class, but each exhibits its own behavior, that's the core idea of polymorphism in OOP. Here is an example where the base class, `Animal`, defines a method called `speak`. This method is implemented by two derived classes (`Dog` and `Cat`), such that the functionality of the method `speak` differs for each class. ```python class Animal: def speak(self): raise NotImplementedError("Subclass must implement abstract method") class Dog(Animal): def speak(self): return "Bark" class Cat(Animal): def speak(self): return "Meow" ``` Now the interesting part of run-time polymorphism is that we do not need to consider that `Cat` and `Dog` are two different classes when we are using the method `speak`. Since both of them implement the same method signature, we can type define any function that expects one of these objects as input using the parent class, `Animal`. The function will then be able to take in an object from either of the child classes as input. ```python def animal_sound(animal: Animal): print(animal.speak()) # Polymorphism in action dog = Dog() cat = Cat() animal_sound(dog) # Output: Bark animal_sound(cat) # Output: Meow ``` --- # References