B3.2.2 Polymorphism in code
HL onlyCommand term: Construct1. 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
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.
7. 45-second speed round: which overload runs?
Each version of f returns its number. A wrong answer costs 3 seconds.
| Method | LibraryItem | Book | DVD | Magazine |
|---|
Expected output
Until TODO 4 returns a list, the tests stop with a TypeError (the loop cannot iterate over None).
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
isinstanceorif type ==. What would you have to change to add an Audiobook at 0.50 a day? total_fees(days)andtotal_fees(days, 0.5)behave like two overloads. How does Python achieve that with one method?
Check my code
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.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
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):
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
Model solution
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))
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):
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
Model solution
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")
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):
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
Model solution
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:
- Explain the principle of polymorphism and how it makes code flexible and reusable.
- Construct dynamic polymorphism through method overriding, where the version that runs is chosen at run time by the object's actual class.
- Construct static polymorphism through method overloading in Java, where the version is chosen at compile time from the argument types.
- Trace polymorphic calls, distinguishing the declared (reference) type from the actual object type.
- 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 ofprintInt,printString... - Python has no overloading: a second
defwith the same name replaces the first. Use default parameters,*argsor keyword arguments instead.
Why it matters
- Flexibility: a loop over a list of LibraryItems works for every type, with no
ifon 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) | |
|---|---|---|
| Where | superclass and subclass | usually the same class |
| Signature | same name, same parameters | same name, different parameters |
| Decided | at run time, by the object's class | at compile time, by argument types |
| Needs inheritance? | yes | no |
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]
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]
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]
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());
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]
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]