Skip to the workspace
Pebellslearn by building
Object-Oriented Programming  ›  Lesson

Inheritance

Inheritance 14 minInheritance lets a subclass reuse and specialise a parent class, and it is only safe when the subclass truly is a kind of the parent in every situation.

software design architecture / Inheritance

Explore each scene at your own pace.

01 · The rule

The rule

Inheritance

Shelfwise starts selling e-books. They have a title, a price and an author like paper books, but no weight and no shipping. Copying the whole Product class and editing it would create two copies of the same knowledge. Inheritance lets EBook reuse what Product already has and change only what differs. Used carelessly, it also creates some of the worst tangles in object-oriented code.

The rule

Inherit only when "is a" holds everywhere the parent is used.

A subclass inherits the fields and methods of its parent (or base) class, can add new ones, and can override methods to behave differently.

class Product:
    def __init__(self, title, price):
        self.title = title
        self.price = price

    def delivery_days(self):
        return 3

class EBook(Product):
    def __init__(self, title, price, file_url):
        super().__init__(title, price)   # reuse the parent's setup
        self.file_url = file_url

    def delivery_days(self):             # override
        return 0

EBook gets title and price for free, adds file_url, and replaces delivery_days. Any code that works with a Product also works with an EBook, because an e-book is a product.

Inheritance is a tight bond. The subclass depends on the parent's inner workings, so a change to the parent can break every child. That is why the "is a" test has to hold everywhere, not just in one sentence:

  • EBook(Product): an e-book is a product wherever products are listed, priced and ordered. Good.
  • Cart(list): a cart uses a list, but inheriting hands callers sort, clear and insert, which skip every cart rule. Bad.
  • Customer(Address): a customer has an address. Bad.

When the honest phrase is "has a" or "uses a", hold the other object in a field instead.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.