Notes
The problem
Our game has goblins and armoured knights. Both have a name and health, both take hits, and both can die. Written separately, the health code is copied into each class. Fix a bug in one, like health going below zero, and you must remember the other. With ten enemy types, that is ten copies of the same rules, slowly drifting apart.
class Goblin {
int health = 30;
void takeHit(int d) {
health = Math.max(0, health - d); }
boolean alive() { return health > 0; }
}
class ArmoredKnight {
int health = 80;
void takeHit(int d) { ...same... }
boolean alive() { ...same... }
} The idea
Inheritance lets a new class reuse and specialise an existing one. The common part goes into a parent class, Enemy, and Goblin and ArmoredKnight extend it. Use the is a test, and use it strictly. A goblin is a kind of enemy, and it can be used anywhere the game expects an enemy. If that sentence feels forced, inheritance is probably the wrong tool.
- inheritance: a new class
- reuses and specialises an
- existing class
- the test: is a goblin
- truly a kind of enemy,
- everywhere an enemy is
- used? yes: extends is ok
- parent = superclass
- child = subclass
The base class
The base class holds what every enemy shares: a name, health, taking a hit and being alive. Health is private, so even subclasses cannot set it directly, and the base class keeps the rule that it never drops below zero. It is abstract because a plain enemy makes no sense in the game, and it declares an abstract taunt method that each subclass must write.
abstract class Enemy {
private final String name;
private int health;
Enemy(String name, int health) {..}
void takeHit(int damage) {
health = Math.max(0, health - damage);
}
final boolean alive() { .. }
abstract String taunt();
} extends and super
Goblin extends Enemy. It inherits take hit and alive, and adds its own field and method for stealing coins. Constructors are not inherited, so the goblin constructor calls super with a name and thirty health. That call must be the first line, because the parent part of the object has to be built before the child part. If you leave it out, Java tries to call a parent constructor with no arguments.
class Goblin extends Enemy {
private int stolenCoins;
Goblin(String name) {
super(name, 30); // must be first
}
void steal(int coins) { .. }
@Override String taunt() {
return "Shiny coins!";
}
} Overriding
The armoured knight overrides take hit. Its armour halves the damage, then it calls super dot take hit to reuse the parent's rule about health. Overriding rules: same name and parameter types, the same or a more specific return type, the same or wider visibility, and no new checked exceptions. Always write the Override annotation, so the compiler catches a typo that would quietly create a new method instead.
@Override
void takeHit(int damage) {
super.takeHit(damage / 2); // armour
}
rules for an override:
same name and parameters
same or narrower return type
same or wider visibility
no new checked exceptions Run-through
The game loop keeps a list of enemies and deals twenty damage to each. For the goblin, the inherited take hit runs and it drops from thirty to ten. For the knight, Java runs the overriding version, which halves the damage and passes ten to the parent. The loop never checks which kind of enemy it has. That is polymorphism, the topic of the next lesson.
protected and final
Protected makes a member visible to subclasses and to the same package. Use it for deliberate hooks that subclasses are meant to use, not for fields. A protected health field would let any subclass set health to minus fifty and break the rule. Final works the other way. A final method, like alive, cannot be overridden. A final class, like String, cannot be extended at all.
- protected: visible to
- subclasses (and package)
- use for hooks, not fields
- final method: cannot be
- overridden (alive)
- final class: cannot be
- extended (String)
- protected fields: anyone who
- extends can break invariants
Single inheritance
In Java a class extends exactly one class. If you do not write extends, the parent is Object, so every chain ends there, and that is why every object has equals, hashCode and toString. A class cannot extend two classes, which avoids confusion about which parent's fields and code win. It can implement many interfaces, which we compare in lesson six.
- a class extends exactly one
- class; Object if you say
- nothing
- Object gives equals, hashCode,
- toString to everyone
- many interfaces: allowed
- many parent classes: not
- allowed (no diamond of state)
Fragile base class
Now the classic trap. Version one of Enemy has take hits, which calls take hit once per hit, so the knight's armour applies. Someone makes it faster in version two: add up all the hits and subtract once. The parent still looks correct, and its own tests pass. But the knight's override is no longer called, so armour silently stops working. The child depended on how the parent was written inside.
// v1: knight armour works
void takeHits(int[] hits) {
for (int h : hits) takeHit(h);
}
// v2: "faster", sums first
void takeHits(int[] hits) {
health -= sum(hits); // no takeHit!
}
// knight now takes full damage Why it is fragile
Why is this so dangerous? A caller of a class only depends on its public methods. A subclass depends on much more: which methods call which, in what order, and every protected member. So the parent can no longer change freely. The safe rule is: either design a class for inheritance on purpose and document which methods call which, or make it final so nobody can extend it.
- a subclass is coupled to:
- which methods call which
- the order of those calls
- the protected members
- the parent cannot change
- freely any more
- rule: design for inheritance
- and document it, or make
- the class final
Misuse in the JDK
Even the Java library has made this mistake. Stack extends Vector, so a stack also has insert element at, and anyone can push into the middle of a stack. The Java documentation now suggests Deque instead. Properties extends Hashtable, so put accepts values that are not strings, which then break the properties methods. In both cases the goal was code reuse, but a true is a relationship was not there.
- java.util.Stack extends Vector
- a stack exposes
- insertElementAt(..), so
- anyone can add in the middle
- Properties extends Hashtable
- put() accepts non-String
- values, which break it
- reuse was the goal; is-a
- was not true
When to use it
Inheritance works well when the is a relationship is real, the hierarchy is shallow, and you own both the parent and the children. An abstract base class with a fixed algorithm and a few hooks is a good example. It goes wrong when the only goal is to borrow three methods, when chains grow five levels deep, or when you extend a class from a library you do not control. For reuse, composition is usually safer.
- good:
- real is-a, used anywhere
- the parent is used
- shallow: one or two levels
- you own both classes
- template-style abstract base
- bad:
- "I want those 3 methods"
- deep chains, 5 levels
- extending library classes
In interviews
In design rounds, chess pieces, library items and vehicles are common hierarchies. Ask whether the children differ in behaviour or only in data. If a car and a bike only differ in size, a field or an enum is simpler than subclasses. Interviewers look for shallow trees, real is a relationships and private state. Deep trees, a subclass for every small variation, and protected mutable fields are warning signs.
- parking lot: Vehicle ->
- Car, Bike, Truck (often
- better as an enum or field)
- chess: Piece -> Rook, King
- library: Item -> Book, DVD
- mistakes: deep trees,
- subclass per small variation,
- protected mutable fields