LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · PILLAR · 4 OF 48

Inheritance in Java: extends, super, Overriding and Its Pitfalls

How inheritance works in Java and where it goes wrong, shown with enemies in a small game: the is-a test, extends and super, constructor chaining, overriding rules, protected members, final, single inheritance, the fragile base class problem where a harmless change in a parent breaks a child, and misuse inside the JDK itself, with Java 17 code.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 173 lines, with a small main() demo. Save it as InheritanceDemo.java, then run javac InheritanceDemo.java && java InheritanceDemo.

import java.util.List;

/**
 * Inheritance with game enemies.
 * Part 1: Goblin and Knight copied the same health code (shown in comments below).
 * Part 2: an abstract Enemy base class, two subclasses, super and overriding.
 * Part 3: the fragile base class problem - a "harmless" change in the parent breaks a child.
 */
public class InheritanceDemo {

    public static void main(String[] args) {
        // Part 1 (the problem) in words: before Enemy existed, Goblin and ArmoredKnight each had
        // their own health field, takeHit and alive methods - the same rules copied twice.

        // ---------- Part 2: the clean version ----------
        Goblin goblin = new Goblin("Snik");
        ArmoredKnight knight = new ArmoredKnight("Sir Brass");
        List<Enemy> wave = List.of(goblin, knight);

        for (Enemy e : wave) {
            e.takeHit(20);   // Goblin uses the inherited version, the knight its override
            System.out.println(e + " says: " + e.taunt());
        }
        goblin.steal(5);
        System.out.println("Goblin stole " + goblin.stolenCoins() + " coins");
        System.out.println("Every Enemy is also an Object: " + (goblin instanceof Object));

        // ---------- Part 3: fragile base class ----------
        KnightV1 safe = new KnightV1();
        KnightV2 broken = new KnightV2();
        int[] volley = {10, 10, 10};
        safe.takeHits(volley);
        broken.takeHits(volley);
        System.out.println("Parent v1 -> knight health " + safe.health() + " (armour applied)");
        System.out.println("Parent v2 -> knight health " + broken.health() + " (armour skipped!)");
    }
}

/** Shared state and behaviour live once, here. Abstract: there is no "plain" enemy. */
abstract class Enemy {
    private final String name;
    private int health;            // private: subclasses cannot break the "never below 0" rule

    Enemy(String name, int health) {
        if (health <= 0) {
            throw new IllegalArgumentException("health must be positive");
        }
        this.name = name;
        this.health = health;
    }

    /** Subclasses may override; the rule about health stays here. */
    void takeHit(int damage) {
        if (damage < 0) {
            throw new IllegalArgumentException("damage cannot be negative");
        }
        health = Math.max(0, health - damage);
    }

    /** final: no subclass can redefine what "alive" means. */
    final boolean alive() {
        return health > 0;
    }

    final int health() {
        return health;
    }

    /** Each kind of enemy must provide its own taunt. */
    abstract String taunt();

    @Override
    public String toString() {
        return getClass().getSimpleName() + " " + name + " [" + health + " hp, alive=" + alive() + "]";
    }
}

class Goblin extends Enemy {
    private int stolenCoins;

    Goblin(String name) {
        super(name, 30);           // parent part is built first
    }

    void steal(int coins) {
        if (alive()) {
            stolenCoins += coins;
        }
    }

    int stolenCoins() {
        return stolenCoins;
    }

    @Override
    String taunt() {
        return "Shiny coins!";
    }
}

class ArmoredKnight extends Enemy {
    ArmoredKnight(String name) {
        super(name, 80);
    }

    /** Overrides the parent, then reuses it with super. Armour halves the damage. */
    @Override
    void takeHit(int damage) {
        super.takeHit(damage / 2);
    }

    @Override
    String taunt() {
        return "My armour laughs at you.";
    }
}

// ---------- Part 3: fragile base class ----------

/** Version 1 of a parent: takeHits calls takeHit for each hit. */
class EnemyV1 {
    private int health = 100;

    void takeHit(int damage) {
        health = Math.max(0, health - damage);
    }

    void takeHits(int[] hits) {
        for (int h : hits) {
            takeHit(h);            // the subclass override runs here
        }
    }

    int health() {
        return health;
    }
}

/** Version 2: someone made takeHits "faster". Its own behaviour looks identical. */
class EnemyV2 {
    private int health = 100;

    void takeHit(int damage) {
        health = Math.max(0, health - damage);
    }

    void takeHits(int[] hits) {
        int total = 0;
        for (int h : hits) {
            total += h;
        }
        health = Math.max(0, health - total);   // no longer calls takeHit!
    }

    int health() {
        return health;
    }
}

class KnightV1 extends EnemyV1 {
    @Override
    void takeHit(int damage) {
        super.takeHit(damage / 2);
    }
}

/** The exact same subclass code, now silently broken by the parent's change. */
class KnightV2 extends EnemyV2 {
    @Override
    void takeHit(int damage) {
        super.takeHit(damage / 2);
    }
}

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.

Copy and paste
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.

In one sentence
  • 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
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
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.

class ArmoredKnight
@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.

Access for subclasses
  • 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.

Java rules
  • 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.

Version 2 of the parent
// 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.

The real cost
  • 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.

Real examples
  • 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 vs bad uses
  • 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.

Where it shows up
  • 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

Interview questions

What is inheritance and what does the is-a relationship mean?

Inheritance lets a subclass reuse and extend the fields and methods of a superclass using extends. The is-a test asks whether the subclass is truly a kind of the parent and can be used anywhere the parent is expected. If it cannot, inheritance is the wrong choice.

What does the super keyword do?

super(...) calls a parent constructor and must be the first statement in a constructor. super.method() calls the parent's version of an overridden method, which lets a subclass add to the parent's behaviour instead of replacing it.

What are the rules for overriding a method in Java?

The overriding method must have the same name and parameter types, the same or a covariant return type, the same or less restrictive access, and must not throw broader checked exceptions. Static, private and final methods cannot be overridden. Use @Override so the compiler checks it.

What is the fragile base class problem?

Subclasses depend on the internal behaviour of their parent, such as which methods call which. A change inside the parent that keeps its public behaviour can still break subclasses, for example by no longer calling a method that a subclass overrides.

Why does Java not support multiple inheritance of classes?

Inheriting from two classes can bring two different implementations and two copies of state for the same member, the diamond problem. Java avoids that by allowing one superclass but many interfaces, which mostly carry contracts and, at most, default methods without instance state.

Are constructors inherited?

No. Each class declares its own constructors, and every constructor must call a superclass constructor first, either explicitly with super(...) or implicitly with a no-argument super(). If the parent has no no-argument constructor, the child must call one explicitly.

Give an example of inheritance misuse in the Java standard library.

java.util.Stack extends Vector, so it exposes methods like insertElementAt that break stack behaviour; Deque is recommended instead. Properties extends Hashtable, so put can store non-String values that the String-based methods then ignore.

When should you make a class final?

When it is not designed for extension, for example a value type like String or a class whose invariants would be broken by overriding. Making it final prevents fragile subclasses and leaves you free to change its internals later.