Unit 3 · OOP Concepts

3.5Inheritance

Inheritance lets a new class (the subclass, child or derived class) acquire the attributes and methods of an existing class (the superclass, parent or base class). It models an is-a relationship: a Dog is an Animal.

Benefits: code reuse, logical organisation and easy extension.

Why inheritance?

Suppose you need Car, Bus and Motorbike classes. All three have a registration number, a make and a speed, and all three can start() and stop(). Without inheritance, you would copy the same code three times, and every bug fix would have to be made three times. With inheritance, you write the shared code once in a Vehicle class, and each subclass adds only what is different (a bus has a passenger capacity, for example).

Key words in this topic

  • Superclass (parent, base class) and subclass (child, derived class).
  • extends: the keyword that makes one class inherit from another.
  • super: the keyword that refers to the parent's constructor or methods.
  • is-a: the test for inheritance. If "a Car is a Vehicle" is true, inheritance may fit.
  • Overriding: a subclass replacing an inherited method with its own version.

In this section