Home › Theme B › B3 › B3.2 › B3.2.2

B3.2.2 Polymorphism in code

HL onlyCommand term: Construct

1. Dynamic polymorphism: decided at run time

Every variable below is declared as a LibraryItem, but each refers to a different kind of object. Step through and watch the two checks: the compiler looks at the declared type; at run time the JVM looks at the actual object and runs that class's version.

The classes used (Java and Python)

2. Static polymorphism: overloading, decided at compile time

Java lets one class have several methods with the same name but different parameter lists. The compiler picks one from the types of the arguments: an exact match first, otherwise a safe widening (int to long to double, char to int). Choose a call.

Java: FineCalc

Python has no overloading

Choose a call.

3. Adding a new type: if-chains versus polymorphism

The library starts lending audiobooks. Compare a design that tests the type with if statements against one where each class answers for itself. Red lines are changes to existing, working code; green lines are new code.

Type checks with if

Polymorphism

4. One loop, many forms: the shape painter

Add shapes to the list, then run the loop. The loop only ever says shape.draw() and shape.area(); each object answers in its own way.

5. Flip-card deck

Click to flip. Say the answer before you flip.

6. Overriding, overloading or neither?

Classify each description. Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: which overload runs?

Each version of f returns its number. A wrong answer costs 3 seconds.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 7, task 2 (HL). Late fees differ by item type: books cost 0.20 a day, DVDs 1.00 a day, and magazines are never lent. Build a Library class whose methods work on any LibraryItem without ever asking what type it is. Each subclass overrides small methods; the base class does the shared calculation, with an optional discount parameter instead of overloading.
MethodLibraryItemBookDVDMagazine

Expected output

Until TODO 4 returns a list, the tests stop with a TypeError (the loop cannot iterate over None).

Dune by Herbert: 2.0 Up (96 min): 3.0 Wired issue 42: 0.0 Emma by Austen: 0.0 5.0 2.5 ['Book', 'DVD', 'Book']

Think about it

  • late_fee() is written once, in LibraryItem, yet gives a different answer for each type. Which call inside it is polymorphic?
  • Library contains no isinstance or if type ==. What would you have to change to add an Audiobook at 0.50 a day?
  • total_fees(days) and total_fees(days, 0.5) behave like two overloads. How does Python achieve that with one method?

Check my code

    Next (B3.2.3): abstraction. Should anyone ever create a plain LibraryItem? An abstract class can forbid it and force every subclass to provide its own daily_fee().

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: One call, many shapes

    Write classes Circle, Square and Triangle, each with an area() method. Put several shapes in one list and print each area with the same loop. This is polymorphism: the same call runs different code depending on the object.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_2_average.py
    import math
    
    class Circle:
        pass  # your code here
    
    class Square:
        pass  # your code here
    
    class Triangle:
        pass  # your code here
    
    # ---- tests ----
    shapes = [Circle(1), Square(3), Triangle(4, 5)]
    for s in shapes:
        print(type(s).__name__, round(s.area(), 2))
    print(round(sum(s.area() for s in shapes), 2))
    

    Expected output when your code is correct:

    Circle 3.14
    Square 9
    Triangle 10.0
    22.14
    Hint
    The loop does not need to know which kind of shape it has.
    Model solution
    File: b3_2_2_average_solution.py
    import math
    
    class Circle:
        def __init__(self, r):
            self.r = r
        def area(self):
            return math.pi * self.r ** 2
    
    class Square:
        def __init__(self, side):
            self.side = side
        def area(self):
            return self.side ** 2
    
    class Triangle:
        def __init__(self, base, height):
            self.base, self.height = base, height
        def area(self):
            return 0.5 * self.base * self.height
    
    # ---- tests ----
    shapes = [Circle(1), Square(3), Triangle(4, 5)]
    for s in shapes:
        print(type(s).__name__, round(s.area(), 2))
    print(round(sum(s.area() for s in shapes), 2))
    
    Moderate

    Task 2: Notifications by overriding

    ShelfWise reminds students about overdue books. Write a base class Notifier with send(student, message) that returns a string, and subclasses EmailNotifier, SMSNotifier (messages cut to 20 characters) and WeChatNotifier, each overriding send. A function remind_all(notifiers, student, msg) must work with any mix of them.

    Starter file (write your code where it says pass # your code here):

    File: b3_2_2_moderate.py
    class Notifier:
        pass  # your code here
    
    class EmailNotifier(Notifier):
        pass  # your code here
    
    class SMSNotifier(Notifier):
        pass  # your code here
    
    class WeChatNotifier(Notifier):
        pass  # your code here
    
    def remind_all(notifiers, student, msg):
        pass  # your code here
    
    # ---- tests ----
    remind_all([Notifier(), EmailNotifier(), SMSNotifier(), WeChatNotifier()], "Ana", "Dune is 3 days overdue")
    

    Expected output when your code is correct:

    [log] Ana: Dune is 3 days overdue
    [email to Ana] Subject: Library reminder | Dune is 3 days overdue
    [sms to Ana] Dune is 3 days ov...
    [wechat to Ana] 提醒: Dune is 3 days overdue
    Hint
    Adding a new kind of notifier should not require any change to remind_all.
    Model solution
    File: b3_2_2_moderate_solution.py
    class Notifier:
        def send(self, student, message):
            return f"[log] {student}: {message}"
    
    class EmailNotifier(Notifier):
        def send(self, student, message):
            return f"[email to {student}] Subject: Library reminder | {message}"
    
    class SMSNotifier(Notifier):
        def send(self, student, message):
            short = message if len(message) <= 20 else message[:17] + "..."
            return f"[sms to {student}] {short}"
    
    class WeChatNotifier(Notifier):
        def send(self, student, message):
            return f"[wechat to {student}] 提醒: {message}"
    
    def remind_all(notifiers, student, msg):
        for n in notifiers:
            print(n.send(student, msg))
    
    # ---- tests ----
    remind_all([Notifier(), EmailNotifier(), SMSNotifier(), WeChatNotifier()], "Ana", "Dune is 3 days overdue")
    
    Challenging

    Task 3: Operator overloading: Vector

    Write a class Vector for 2D vectors with __add__, __sub__, __mul__ (vector × number), __rmul__ (number × vector), __eq__, __abs__ (length) and __repr__. Use it to move a robot: start at (0, 0), and apply the moves 3 × (1, 0), then (0, 2), then −1 × (1, 1).

    Starter file (write your code where it says pass # your code here):

    File: b3_2_2_challenging.py
    import math
    
    class Vector:
        pass  # your code here
    
    # ---- tests ----
    pos = Vector(0, 0)
    for move in [3 * Vector(1, 0), Vector(0, 2), Vector(1, 1) * -1]:
        pos = pos + move
        print(pos)
    print(abs(Vector(3, 4)), Vector(1, 2) - Vector(1, 2) == Vector(0, 0))
    

    Expected output when your code is correct:

    Vector(3, 0)
    Vector(3, 2)
    Vector(2, 1)
    5.0 True
    Hint
    Python calls __rmul__ when the number is on the left: 3 * v.
    Model solution
    File: b3_2_2_challenging_solution.py
    import math
    
    class Vector:
        def __init__(self, x, y):
            self.x, self.y = x, y
    
        def __add__(self, other):
            return Vector(self.x + other.x, self.y + other.y)
    
        def __sub__(self, other):
            return Vector(self.x - other.x, self.y - other.y)
    
        def __mul__(self, k):
            return Vector(self.x * k, self.y * k)
    
        __rmul__ = __mul__
    
        def __eq__(self, other):
            return self.x == other.x and self.y == other.y
    
        def __abs__(self):
            return math.hypot(self.x, self.y)
    
        def __repr__(self):
            return f"Vector({self.x}, {self.y})"
    
    # ---- tests ----
    pos = Vector(0, 0)
    for move in [3 * Vector(1, 0), Vector(0, 2), Vector(1, 1) * -1]:
        pos = pos + move
        print(pos)
    print(abs(Vector(3, 4)), Vector(1, 2) - Vector(1, 2) == Vector(0, 0))
    

    Learning objectives

    By the end of this page you should be able to:

    1. Explain the principle of polymorphism and how it makes code flexible and reusable.
    2. Construct dynamic polymorphism through method overriding, where the version that runs is chosen at run time by the object's actual class.
    3. Construct static polymorphism through method overloading in Java, where the version is chosen at compile time from the argument types.
    4. Trace polymorphic calls, distinguishing the declared (reference) type from the actual object type.
    5. Explain how polymorphism allows new subclasses to be added without changing existing code.

    The principle

    Polymorphism ("many forms") means one interface, many implementations: the same method call can do different things depending on the object or the arguments. Code can be written against a general type (LibraryItem, Shape, Employee) and still work correctly for every specific type, including ones invented later.

    Dynamic (run-time) polymorphism: overriding

    LibraryItem item = new DVD("Up");     // declared type LibraryItem, actual type DVD
    item.loanDays();                      // compiler: does LibraryItem have loanDays()? yes
                                          // JVM at run time: the object is a DVD, so DVD.loanDays() runs
    item.getMinutes();                    // compile error: LibraryItem has no getMinutes()
    ((DVD) item).getMinutes();            // a cast tells the compiler it is really a DVD
    • A subclass overrides a method by defining one with the same name and parameters.
    • Which version runs is decided at run time by the object's actual class (dynamic binding / dynamic dispatch).
    • The declared type decides which methods may be called; the actual type decides which version runs.
    • Python works the same way, but has no declared types: any object with the right method can be used (duck typing).

    Static (compile-time) polymorphism: overloading

    static double calc(int days)                { return days * 0.2; }
    static double calc(int days, double rate)   { return days * rate; }
    static double calc(double amount)           { return amount; }
    
    calc(5);        // calc(int)
    calc(5, 0.5);   // calc(int, double)
    calc(2.5);      // calc(double)
    calc(5L);       // no long version: long widens to double, so calc(double)
    • Overloaded methods share a name but differ in the number, types or order of parameters. A different return type alone is not enough.
    • The compiler chooses the version from the argument types, so there is no run-time decision.
    • It improves efficiency for the programmer: one memorable name (println, Math.max) for related operations, instead of printInt, printString...
    • Python has no overloading: a second def with the same name replaces the first. Use default parameters, *args or keyword arguments instead.

    Why it matters

    • Flexibility: a loop over a list of LibraryItems works for every type, with no if on the type.
    • Extensibility: adding a new subclass needs no change to existing code that uses the superclass (the open/closed principle).
    • Reusability: general code (sorting, reports, painting) is written once for the superclass type.
    Overriding (dynamic)Overloading (static)
    Wheresuperclass and subclassusually the same class
    Signaturesame name, same parameterssame name, different parameters
    Decidedat run time, by the object's classat compile time, by argument types
    Needs inheritance?yesno

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Distinguish between static and dynamic polymorphism. [4]

    Static polymorphism is method overloading: several methods with the same name but different parameter lists [1], with the version chosen at compile time from the argument types [1]. Dynamic polymorphism is method overriding: a subclass redefines an inherited method with the same signature [1], with the version chosen at run time from the actual class of the object [1].

    2. Construct two overloaded Java methods called area: one that returns the area of a circle from its radius, and one that returns the area of a rectangle from its width and height. [3]

    Both methods named area with different parameter lists [1]; circle version returns Math.PI * r * r [1]; rectangle version returns w * h, both with return type double [1].
    static double area(double r) { return Math.PI * r * r; }
    static double area(double w, double h) { return w * h; }

    3. A payroll program loops through an array of Employee objects and calls pay() on each. Explain how polymorphism lets the company add a new Contractor type without changing the loop. [3]

    Contractor extends Employee and overrides pay() with its own calculation [1]; the loop calls pay() through the Employee type, so it compiles for any subclass [1]; at run time the Contractor's version is chosen automatically by dynamic binding, so the loop needs no change / no type checks [1].

    4. State the output of this Java code, and explain line 3. [3]

    class Animal { String speak() { return "..."; } }
    class Dog extends Animal { String speak() { return "Woof"; } }
    Animal a = new Dog();
    System.out.println(a.speak());
    Output: Woof [1]. Line 3 declares a variable of type Animal that refers to a Dog object, allowed because a Dog is an Animal [1]; at run time the actual object's (Dog's) overriding version of speak() is used [1].

    5. A class has void show(int x), void show(double x) and void show(String s). State which version each call uses: show(4), show(4.0), show('A'). [3]

    show(4): show(int) [1]; show(4.0): show(double) [1]; show('A'): show(int), because char widens to int [1].

    6. Explain why Python does not support method overloading in the same way as Java, and outline how a similar effect can be achieved. [3]

    Python has no declared parameter types, so it cannot choose a method by type [1]; defining a second method with the same name replaces the first [1]; a similar effect is achieved with default parameter values, *args / keyword arguments, or checking the arguments inside one method [1].