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.

The call is written once; who runs is chosen by the object.
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 wayAdding a new kind
A chain of kind checksUpdate every chain in the program
One call that branchesA new file, touching nothing existing

Example 1 — why the loop does not know kinds

  1. It calls the general’s method.
  2. The object chooses the body.
  3. And no kind check is needed.

Example 2 — why a chain of checks is bad

  1. A new kind requires updating every chain.
  2. No one knows how many there are.
  3. And missing one suffices.
A fourth class inheriting from Person would go into the array and work in this loop without a character of it changing.