Learn
B3.2.2 | POLYMORPHISM (HL ONLY)
01 | ONE REQUEST, DIFFERENT BEHAVIOURS
Imagine a school dashboard that displays a status report for every piece of equipment. A robot should report that its scanner is ready. A tablet should report that its screen is ready. A general sensor can use a simple ready message. The dashboard needs all three reports, but it should not need to understand how every device creates its message.
Polymorphism means that one common operation can have different implementations. The caller asks each object to report. The object supplies the appropriate behaviour. In this lesson, the shared operation is report(), and the different implementations belong to Device, Robot and Tablet.
Think of the method name as a request, not as a promise that every object will execute identical instructions. The useful promise is that every object can respond with a status string.
02 | RECALL THE CLASS AND THE OBJECT
A class defines attributes and methods. An object is an individual instance of a class. Robot("R01") creates a Robot object whose identifier is R01. Another Robot object can have a different identifier while sharing the same method definitions.
Inheritance gives a subclass access to suitable behaviour from a superclass. Robot is a kind of Device. Polymorphism builds on this relationship: a routine written to work with Device objects can also work with Robot objects, while still allowing their specialised behaviour.
Do not picture a Robot object turning into a Device during a call. It remains a Robot. A variable or parameter may provide a general way to refer to it.
03 | THE SHARED METHOD CONTRACT
Before writing the subclasses, decide what report() promises. Here it takes no extra arguments, returns a string describing readiness and does not change the device state. Code using the method can print that string without knowing the exact device type.
| Part of the contract | Our decision |
|---|---|
| Operation | report() |
| Inputs | No additional arguments |
| Result | A status string |
| State change | None |
| What may vary | The wording appropriate to each device |
A contract is more than a repeated name. If one subclass returned a number while the dashboard expected text, or unexpectedly erased device settings, callers could fail. Useful polymorphism preserves the expectations that callers rely on.
04 | BUILD THE PYTHON SUPERCLASS
Start with the general case. __init__ stores the identifier on each instance. report returns a complete default message. Return sends a value back to the caller; it does not print the value by itself.
class Device:
def __init__(self, device_id):
self.device_id = device_id
def report(self):
return f"Device {self.device_id}: ready"
self refers to the object receiving the call. When two devices call the same inherited method, self is different for each call, so their identifiers can differ. We keep the attributes simple here to focus on dispatch; the controlled updates from the encapsulation lesson remain useful in larger designs.
05 | OVERRIDE THE METHOD IN A SUBCLASS
class Robot(Device):
def report(self):
return f"Robot {self.device_id}: scan ready"
robot = Robot("R01")
print(robot.report())
# Robot R01: scan ready
Robot inherits Device.__init__ because it does not define its own initializer. Its report method replaces the inherited implementation for ordinary calls on a Robot instance. This is method overriding: a subclass supplies its own implementation of an inherited instance operation.
The method name and usable calling pattern stay the same. We have changed what happens inside the operation, so the caller can continue to use report(). Run this example after the Device definition.
06 | ADD A SECOND SPECIALISATION
class Tablet(Device):
def report(self):
return f"Tablet {self.device_id}: screen ready"
Tablet makes a different choice about the same request. It does not need a method called tablet_report, because the object already supplies the context. Giving all device types a compatible report operation is what lets the dashboard treat them uniformly.
This does not mean every method in unrelated classes must have the same name. Choose a shared operation when the meanings fit a common purpose. Calling unrelated operations report merely to avoid an if statement would make the design harder to understand.
07 | A SUBCLASS CAN KEEP THE DEFAULT
class Sensor(Device):
pass
sensor = Sensor("S01")
print(sensor.report())
# Device S01: ready
pass is an empty statement. Sensor adds no methods here, so ordinary lookup finds report in Device. A subclass does not have to override every inherited method. Reusing the default is appropriate when it already meets the requirements.
The word Device in the output comes from the string written in Device.report. It does not prove that sensor has become a Device-only object. Its actual class remains Sensor.
08 | PUT DIFFERENT OBJECTS IN ONE COLLECTION
fleet = [Robot("R01"), Tablet("T01"), Sensor("S01")]
for device in fleet:
print(device.report())
A list can hold references to different kinds of objects. Each loop iteration assigns the next object reference to device. The body, the indented instructions repeated by the loop, then calls report on that object.
There is one call in the loop body, not a separate instruction for each class. The output is Robot R01: scan ready, then Tablet T01: screen ready, then Device S01: ready. The order follows the list.
09 | HOW THE METHOD IS SELECTED
| Iteration | Actual object | Implementation used | Returned string |
|---|---|---|---|
| 1 | Robot R01 | Robot.report | Robot R01: scan ready |
| 2 | Tablet T01 | Tablet.report | Tablet T01: screen ready |
| 3 | Sensor S01 | Device.report, inherited | Device S01: ready |
For these examples, Python looks for the instance method on the actual object’s class and then along its inheritance order. Robot has a report implementation, so that version runs. Sensor does not, so the inherited Device version runs. This selection occurs as the program executes, so it is dynamic dispatch.
The variable name device does not choose the implementation. Renaming it item would leave the behaviour unchanged. The actual object and the method lookup rules matter.
10 | STEP THROUGH THE POLYMORPHIC LOOP
Predict the next message before stepping. Watch the actual class, the selected implementation and the output. The same call line is used for all three objects.
11 | A COMPLETE PYTHON PROGRAM
Save this as polymorphism_demo.py and run it in your editor. The class definitions come first so they exist before objects are constructed. show_reports is deliberately general: it only relies on each object supporting a compatible report operation.
class Device:
def __init__(self, device_id):
self.device_id = device_id
def report(self):
return f"Device {self.device_id}: ready"
class Robot(Device):
def report(self):
return f"Robot {self.device_id}: scan ready"
class Tablet(Device):
def report(self):
return f"Tablet {self.device_id}: screen ready"
class Sensor(Device):
pass
def show_reports(devices):
for device in devices:
print(device.report())
fleet = [Robot("R01"), Tablet("T01"), Sensor("S01")]
show_reports(fleet)
No real sensors or hardware are needed. The messages simulate different behaviours so you can concentrate on which implementation runs. Printing happens in show_reports, while report methods return values. This separates producing information from deciding how to display it.
12 | REUSE THE CALLER, NOT JUST THE CLASSES
Now imagine adding a Projector. Without polymorphism, a dashboard might grow a chain of checks: if this is a robot, use one function; else if it is a tablet, use another. Each new type would require changing that central chain.
With a compatible report method, show_reports can remain unchanged. You reuse the loop and its logic as well as the inherited initialization. This makes a new device type easier to add and reduces the number of places that need coordinated edits.
The benefit depends on preserving the shared contract. If a new subclass needs extra mandatory arguments for report, the old zero-argument call will no longer work.
13 | EXTEND THE PROGRAM WITH A PROJECTOR
class Projector(Device):
def report(self):
return f"Projector {self.device_id}: lamp ready"
fleet.append(Projector("P01"))
show_reports(fleet)
Run these statements after the complete Python program. The earlier three messages print again, followed by Projector P01: lamp ready. We changed the available objects, but not the code inside show_reports.
A good construction answer should show both sides of polymorphism: at least two compatible implementations and a common caller that actually uses them. Defining several subclasses without a shared call does not demonstrate the full benefit.
14 | EXTEND AN OVERRIDE WITH SUPER
class LoggingRobot(Robot):
def report(self):
base_message = super().report()
return base_message + " [logged]"
print(LoggingRobot("R03").report())
# Robot R03: scan ready [logged]
This override builds on the existing Robot message instead of duplicating its formatting. In this single-inheritance example, super().report() finds Robot.report. It uses the same LoggingRobot instance; it does not create another robot.
More generally, Python super follows the method resolution order. Calling self.report() inside this report implementation would call the same override again and cause unbounded recursion unless there were an explicit stopping mechanism.
15 | JAVA: DECLARED TYPE AND ACTUAL TYPE
Device device = new Robot("R01");
System.out.println(device.report());
// Robot R01: scan ready
Here Device is the declared type of the variable. Robot is the actual runtime class of the object. The compiler checks that report is available through Device. At runtime, an ordinary overridden instance method is selected using the actual object, so Robot.report runs.
The reference lets the program use a general view of a specialised object. It does not create a second object or remove the robot’s specialised implementation. A Robot-only operation not declared by Device cannot simply be called through this Device variable.
16 | A COMPLETE JAVA PROGRAM
Save this as PolymorphismExample.java. Only PolymorphismExample is public. The other classes are in the same file for this small exercise. Run main using your Java editor. The output matches the complete Python example.
class Device {
protected final String deviceId;
public Device(String deviceId) { this.deviceId = deviceId; }
public String report() { return "Device " + deviceId + ": ready"; }
}
class Robot extends Device {
public Robot(String id) { super(id); }
@Override
public String report() { return "Robot " + deviceId + ": scan ready"; }
}
class Tablet extends Device {
public Tablet(String id) { super(id); }
@Override
public String report() { return "Tablet " + deviceId + ": screen ready"; }
}
class Sensor extends Device {
public Sensor(String id) { super(id); }
}
public class PolymorphismExample {
public static void showReports(Device[] devices) {
for (Device device : devices) {
System.out.println(device.report());
}
}
public static void main(String[] args) {
Device[] fleet = {
new Robot("R01"), new Tablet("T01"), new Sensor("S01")
};
showReports(fleet);
}
}
@Override asks the compiler to check that the method really overrides an inherited method. It helps catch mistakes such as spelling report as reports. Constructors prepare objects; they are not overridden methods.
17 | OVERRIDING HAS RULES
In Java, an overriding method must have a matching signature and a compatible return type. It cannot reduce the access of the inherited method. Here public String report() stays public and returns String in every class. An incompatible parameter list creates a different method rather than overriding the original.
In Python, report(self, prefix) replaces lookup by that name but requires an extra argument. The inherited caller using report() will fail with TypeError. Python does not automatically enforce every behavioural contract when the class is defined, so tests remain essential.
The safe habit in both languages is to preserve how callers use the operation, its expected result and relevant state rules. Syntax alone does not guarantee a sensible substitution.
18 | A DIFFERENT IDEA: METHOD OVERLOADING
Sometimes the caller wants the same operation name with different input patterns. Java supports method overloading: methods share a name but have different parameter lists. The compiler selects an applicable signature using the available argument types. This is commonly called static or compile-time polymorphism.
class LabelMaker {
public String make(String name) {
return "Name: " + name;
}
public String make(String name, int number) {
return "Name: " + name + " #" + number;
}
}
// Inside main:
LabelMaker labels = new LabelMaker();
System.out.println(labels.make("Robot"));
System.out.println(labels.make("Robot", 4));
The calls have one argument and two arguments, so different overloads are selected. A different return type alone cannot distinguish overloads with identical parameter lists. The example class and main statements should be placed in their appropriate locations, not pasted together as top-level statements.
19 | STATIC POLYMORPHISM DOES NOT REQUIRE STATIC METHODS
The word static here describes when a choice is resolved. It does not mean the methods must use Java’s static keyword. LabelMaker.make above uses ordinary instance methods, but the overload signature is selected at compile time.
Java static methods belong to classes and are not dynamically overridden like ordinary instance methods. A same-signature static method in a subclass hides a class method. Avoid presenting static-method hiding as an example of runtime overriding.
The concepts answer different questions: overloading asks which signature is applicable; overriding asks which implementation of an instance method runs for the actual object.
20 | OVERLOADING AND OVERRIDING IN THE SAME CALL
Use Reporter with the earlier Java Device and Robot classes. Put its definition alongside those classes and the final statements inside main.
class Reporter {
public void show(Device device) {
System.out.println("Device overload -> " + device.report());
}
public void show(Robot robot) {
System.out.println("Robot overload -> " + robot.report());
}
}
// Place these statements inside main in PolymorphismExample.
Reporter reporter = new Reporter();
Device item = new Robot("R02");
reporter.show(item);
The output is Device overload -> Robot R02: scan ready. Why two different type names? The compiler sees item declared as Device and selects show(Device). It does not choose show(Robot) simply because the runtime object happens to be a Robot.
Inside that selected method, device.report() is an overridden instance call. Runtime dispatch therefore chooses Robot.report. First select the overload signature; then dispatch the overridden instance method. If you declared Robot item instead, show(Robot) would be selected.
21 | PYTHON DOES NOT OVERLOAD BY REPEATING DEF
class LabelMaker:
def make(self, name, number=None):
if number is None:
return f"Name: {name}"
return f"Name: {name} #{number}"
labels = LabelMaker()
print(labels.make("Robot"))
print(labels.make("Robot", 4))
An optional argument lets one Python implementation accept two calling patterns. This is not Java-style compile-time overload resolution. Defining make twice in the same Python class would bind the name to the later definition, rather than retain a set of signatures selected from argument types.
Python typing.overload can describe multiple type-checking signatures, but a runtime implementation is still needed. Do not assume those annotations create Java-style runtime implementations. For this course example, one clearly documented optional parameter is enough.
22 | POLYMORPHISM WITHOUT A SHARED SUPERCLASS
class WeatherStation:
def report(self):
return "Weather: dry"
show_reports([Robot("R01"), WeatherStation()])
Python can call report on WeatherStation even though it does not inherit Device. This style is often called duck typing: what matters to this caller is that the object supports the required operation and meaning.
A number such as 42 would fail because it has no report method. A report method that returned an incompatible result could also break a different caller. A shared superclass can document a family of objects, but Python’s runtime behaviour is not limited to inheritance-based polymorphism.
23 | FLEXIBILITY, REUSE AND EFFICIENCY
Polymorphism lets a stable caller work with new compatible types. Overriding keeps specialised behaviour near the class that owns it. Overloading gives related input patterns a consistent name and lets a compiler reject calls that match no suitable signature.
Compile-time selection can avoid runtime selection between overload signatures and may support optimisation. However, it does not prove the entire program is faster. An overloaded method can still contain dynamically dispatched calls or an expensive algorithm. Algorithm choice, data size and implementation costs usually matter more than a label such as static or dynamic.
Evaluate efficiency in context. A clear reusable design can reduce duplicated maintenance work, while unnecessary hierarchies or confusing overloads can increase complexity. Measure execution performance when it matters.
24 | TEST BEHAVIOUR THROUGH THE GENERAL INTERFACE
expected = [
"Robot R01: scan ready",
"Tablet T01: screen ready",
"Device S01: ready"
]
actual = [device.report() for device in fleet[:3]]
assert actual == expected
assert isinstance(fleet[0], Device)
assert type(fleet[0]) is Robot
Run this after creating the original fleet. The first assertion checks the three returned strings. The next two show that a Robot is usable as a Device while still having Robot as its exact class. An assertion raises an error if its condition is false.
Also test the inherited default and a newly added subclass. For state-changing methods, check postconditions and rejected requests as well as returned values. A trace should follow the actual code rather than assume every subclass uses the base implementation.
25 | COMMON ERRORS AND HOW TO REPAIR THEM
| Mistake | Why it fails | Repair |
|---|---|---|
| Call every method a different name | The caller cannot use one shared operation | Define a meaningful compatible report method |
| Assume a Device reference forces Device.report | It confuses declared and runtime types | Use actual type for ordinary overridden instance dispatch |
| Change required parameters in an override | Existing calls no longer fit | Preserve the calling contract |
| Use return type alone to overload Java | Identical parameter lists still conflict | Choose different suitable parameters |
| Repeat Python def to make overloads | The later definition replaces the earlier binding | Use one implementation with suitable arguments |
| Call self.report inside its own override | It calls itself again | Use super when extending inherited behaviour |
26 | CONSTRUCT YOUR OWN POLYMORPHIC SOLUTION
Build a classroom notification system. Notification defines message(), returning a string. EmailNotification and ScreenNotification override it. A function or method receives a collection of notifications and prints message() for each. Add a third type without changing that caller.
Then, in Java, overload a separate send operation for one recipient and a collection of recipients. Explain which signature the compiler selects and which instance methods remain dynamically dispatched. In Python, implement the alternative calling pattern with one suitable function rather than repeated definitions.
Your explanation should link design to benefit: the shared caller is reusable because it relies on a compatible interface; therefore a new notification type can supply its own implementation without rewriting the loop. The next lesson develops abstraction and abstract classes.