Programming Polymorphism

  • To implement polymorphism in code, you need a solid grasp of object-oriented programming, especially inheritance and method overriding

Run-time polymorphism

  • This happens when a subclass overrides a method defined in a superclass, and the correct version is chosen at run-time, not compile-time

How do you Define Polymorphism?

Example scenario: Animal, Dog, and Cat

Step-by-step logic (pseudocode)

  1. Define a superclass called Animal with a method speak() that does nothing
  2. Create subclasses called Dog and Cat that inherit from Animal
  3. In each subclass, override the speak() method to provide a specific output
  4. Write a function make_sound(animal) that accepts an object of type Animal and calls its speak() method
  5. Create instances of Dog and Cat, and pass them to make_sound()
CLASS Animal
    METHOD speak()
        // Empty method (acts as a placeholder)

CLASS Dog EXTENDS Animal
    METHOD speak()
        OUTPUT "Woof"

CLASS Cat EXTENDS Animal
    METHOD speak()
        OUTPUT "Meow"

PROCEDURE make_sound(animal : Animal)
    CALL animal.speak()

// Create objects
DECLARE myDog : Dog
DECLARE myCat : Cat

SET myDog TO NEW Dog()
SET myCat TO NEW Cat()

// Demonstrate polymorphism
CALL make_sound(myDog)  // Outputs: Woof
CALL make_sound(myCat)  // Outputs: Meow
  • Animal is a base class with a speak() method
  • Dog and Cat are subclasses that override the speak() method
  • make_sound() takes an Animal object but calls the correct version of speak() depending on whether it’s a Dog or a Cat
  • This demonstrates run-time polymorphism – the method call is resolved based on the actual type of the object

Python

class Animal:
    def speak(self):
        pass  # Placeholder method
 
class Dog(Animal):
    def speak(self):
        print("Woof")
 
class Cat(Animal):
    def speak(self):
        print("Meow")
 
def make_sound(animal):
    animal.speak()
 
dog = Dog()
cat = Cat()
 
make_sound(dog)  # Outputs: Woof
make_sound(cat)  # Outputs: Meow
  • This shows method overriding
  • The make_sound() function relies on dynamic method binding

Java

class Animal {
    public void speak() {
        // Empty default method
    }
}
 
class Dog extends Animal {
    @Override
    public void speak() {
        System.out.println("Woof");
    }
}
 
class Cat extends Animal {
    @Override
    public void speak() {
        System.out.println("Meow");
    }
}
 
public class Main {
    public static void makeSound(Animal animal) {
        animal.speak();
    }
 
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
 
        makeSound(dog); // Outputs: Woof
        makeSound(cat); // Outputs: Meow
    }
}
  • Recognise use of a superclass reference (Animal animal) pointing to a subclass object
  • Polymorphism occurs when animal.speak() dynamically calls the correct overridden method