Grade 11 Computer Science · Polymorphism and interfaces
One call, many behaviours
Why inheritance’s second gain matters more than the first.
A loop that does not know what it runs
Three lines of a loop call one method, and on each turn a different body runs. There is no condition and no kind check in the loop, and if a fourth kind is added tomorrow it will work with it without a character of it changing. The question is who exactly decides which body runs.
In the previous unit we said inheritance’s second gain would be revealed here. Here it is: you write one loop calling one method, and at each turn a different body runs — because at each turn the object is of a different kind. Not a line in the loop knows which kinds exist.
Person[] people = {
new Person("dana"),
new Student("omar", 11),
new Teacher("lea", "maths"),
};
for (Person p : people) {
System.out.println(p.describe()); // a different body each turn
}What this replaces
Without this tool, the loop would look different: a chain of checks “if it is of this kind then thus, and if of that kind then thus”. That chain works, and it has one fatal drawback — when a new kind is added one must find and update every such chain in the whole program, and no one knows how many there are. With this tool, a new kind is written in one new file, and not one existing line is touched.
| The way | Adding a new kind |
|---|---|
| A chain of kind checks | Update every chain in the program |
| One call that branches | A new file, touching nothing existing |
Example 1 — why the loop does not know kinds
- It calls the general’s method.
- The object chooses the body.
- And no kind check is needed.
Example 2 — why a chain of checks is bad
- A new kind requires updating every chain.
- No one knows how many there are.
- And missing one suffices.