Grade 11 Computer Science · Inheritance

Extending instead of copying

The tool, and the one test settling whether it may be used.

One sentence that permits or forbids

You have two almost identical classes, and the clever route seems to be that one gets all the other’s code. Sometimes that is right, and sometimes it is a mistake that shows only when someone relies on what looks shared. The test is one sentence — and one small word in it disqualifies everything.

You have two classes that are very alike and differ in little. The first temptation is to copy the shared code into both, and that produces exactly what you learned to flee — the same rule in two places, one of which will not be updated. The tool solving this is inheritance, and it has one clear condition of entry.

The arrow points from the particular to the general, and means “is a kind of”.
public class Person {
    private String name;
    public Person(String name) { this.name = name; }
    public String getName() { return this.name; }
}

public class Student extends Person {   // every student is a person
    private int year;
    public Student(String name, int year) {
        super(name);                    // the general part first
        this.year = year;
    }
}

What this buys

Two things. The first is one source of truth — the shared code is in one place, and a fix in it fixes all the heirs. The second matters more and will be revealed fully in the next unit: every place in the code that knows how to work with the general knows how to work with every particular too, without anyone updating it. A function taking a person will take a student with no change. That is exactly what makes the “is a kind of” test a condition and not a recommendation.

The sentenceTrue alwaysInheritance fits
Every student is a personYesYes
Every rectangle is a shapeYesYes
Every car is an engineNoNo

Example 1 — why copying is bad

  1. The same rule sits in two places.
  2. A fix in one does not reach the other.
  3. And they diverge in silence.

Example 2 — why a car does not inherit from an engine

  1. A car has an engine.
  2. It is not a kind of engine.
  3. And the sentence does not hold.
The qualification will come back exactly where someone relies on b and receives an a.