B3.2.2

Construct code to model polymorphism and its various forms, such as method overriding

Polymorphism means code can take many forms . Which method version is used depends on:

3 min read473 words

What Is Polymorphism?

Polymorphism means code can take many forms. Which method version is used depends on:

  • the object type
  • or the number/type of parameters passed

Smartphone metaphor from the notes: one phone, many roles (map, call, weather, messaging, gaming, social media).

Advantages and Disadvantages

TypePoint
AdvantageCode reuse through common parent/class interfaces
AdvantageLess code duplication (same method name, multiple behaviors)
AdvantageEasier generic programming (treat many objects as a common type)
AdvantageBetter maintainability when behavior is centralized
DisadvantageHigher runtime cost in dynamic dispatch scenarios
DisadvantageIncreased code complexity if poorly designed

Static Polymorphism (Compile-time)

Also called compile-time polymorphism:

  • method selected based on parameter list/signature
  • often described as method overloading

Example idea from the notes (Salesperson):

  • calculateWage() for fixed salary
  • calculateWage(monthlySales) for commission-based salary

Dynamic Polymorphism (Runtime)

Also called runtime polymorphism:

  • happens in inheritance hierarchies (is-a)
  • subclass provides a method with the same name as superclass
  • actual method used is decided at runtime
  • commonly called method overriding

Example idea from the notes: subclass overrides superclass toString() behavior.

Rules highlighted in the notes:

  • superclass and subclass must have an inheritance relationship
  • overridden method name must be the same
  • method signature compatibility matters between parent and child
  • static methods are not overridden in Java-style OOP

Duck Typing in Python

Python often uses duck typing:

  • behavior depends on whether an object has the required methods/attributes
  • actual declared type is less important

This makes code flexible and reusable for different object types.

Python Examples (Polymorphism)

1. Dynamic Polymorphism via Method Overriding

class Animal:
    def speak(self) -> str:
        return "Some sound"


class Dog(Animal):
    def speak(self) -> str:
        return "Woof"


class Cat(Animal):
    def speak(self) -> str:
        return "Meow"


for animal in [Dog(), Cat(), Animal()]:
    print(animal.speak())

2. Python-style “Static-like” Polymorphism with Default Parameter

class Salesperson:
    def calculate_wage(self, monthly_sales: float | None = None) -> float:
        base = 3000.0
        if monthly_sales is None:
            return base
        return base + 0.10 * monthly_sales


sp = Salesperson()
print(sp.calculate_wage())         # fixed salary
print(sp.calculate_wage(5000.0))   # base + commission

3. Duck Typing Example

class Duck:
    def waddle(self):
        return "Duck waddles"


class Goose:
    def waddle(self):
        return "Goose waddles"


def make_it_waddle(bird):
    return bird.waddle()  # No explicit type check


print(make_it_waddle(Duck()))
print(make_it_waddle(Goose()))

Start typing to search all published objectives.