Find a course

Module 3: Inheritance and PolymorphismLesson 6 of 1214 min

Inheritance: Extending Classes

Build subclasses with extends and super, override methods safely, and use the is-a test to decide when inheritance actually fits your model.

Step 1 of 12Learn

Reusing a class by extending it

A bank has ordinary accounts, savings accounts that earn interest, and checking accounts that charge a fee per withdrawal. All three need a balance, deposits and withdrawals. Copying that code three times means fixing every future bug three times.

Inheritance lets one class build on another. The existing class is the superclass (also called parent or base class); the new one is the subclass (child or derived class). The subclass automatically gets the superclass's fields and methods and can add its own.

class Account {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  deposit(amount) { this.balance += amount; }
  withdraw(amount) {
    if (amount > this.balance) throw new Error('Insufficient funds');
    this.balance -= amount;
  }
}

class SavingsAccount extends Account {
  constructor(owner, balance, rate) {
    super(owner, balance);   // run Account's constructor first
    this.rate = rate;
  }
  addInterest() { this.deposit(this.balance * this.rate); }
}

const s = new SavingsAccount('Lee', 1000, 0.03);
s.deposit(200);      // inherited from Account
s.addInterest();     // balance: 1200 + 36 = 1236

extends sets up the relationship. super(...) calls the parent constructor, and in JavaScript a subclass constructor must call it before touching this. Python writes the same thing as class SavingsAccount(Account): with super().__init__(owner, balance).

Class hierarchy: Account at the top, SavingsAccount and CheckingAccount below itAccountbalance, deposit()SavingsAccountrate, addInterest()CheckingAccountfee, withdraw()

Step 2 of 12Practice · Work it out

Using the classes above, a program runs: const s = new SavingsAccount('Mo', 500, 0.04); s.deposit(100); s.addInterest(); s.withdraw(50);. What is s.balance at the end, in dollars?

Step 3 of 12Practice · Diagram

The account hierarchy

Which class owns the overdraft rule that both subclasses rely on?

Tap the shape that answers the question, then press Check.

The account hierarchyHierarchy diagram: Account, SavingsAccount, CheckingAccount.AccountSavingsAccountCheckingAccount
Account

owner, balance, deposit(), withdraw() with the overdraft check.

SavingsAccount

Adds rate and addInterest().

CheckingAccount

Overrides withdraw() to add a fee, calling super.withdraw().

Step 4 of 12Learn

Overriding methods and calling super

A subclass can override a method by defining one with the same name. When the method is called on a subclass instance, the subclass version runs.

class CheckingAccount extends Account {
  constructor(owner, balance, fee) {
    super(owner, balance);
    this.fee = fee;
  }
  withdraw(amount) {
    super.withdraw(amount + this.fee);   // reuse the parent's checks
  }
}

const c = new CheckingAccount('Ana', 100, 2);
c.withdraw(30);   // balance is now 68

The override uses super.withdraw(...) to run the parent's version, including its overdraft check, and adds the fee on top. That pattern, extend rather than replace, is usually the safest way to override: the subclass keeps every rule the parent enforces and adds its own.

When the override rewrites the logic from scratch instead, the parent's rules can quietly disappear. If CheckingAccount.withdraw had simply done this.balance -= amount + this.fee, the overdraft protection would be gone for checking accounts only, and nobody reading Account would notice.

Some languages make overriding explicit. Java has the @Override annotation, and C# requires virtual on the parent method and override on the child. Both catch typos: a method called withdrawl in the subclass would silently be a new method in JavaScript, but a compile error in C#.

Step 5 of 12Practice · Code challenge

Animal is given. Write a subclass Dog that extends Animal. Its constructor takes name and breed, passes name to the parent and stores breed. Override describe() so that it returns the parent's description followed by " (a <breed>)", for example "Rex says hello (a beagle)".

Runs in a sandbox in your browser.
  • new Dog("Rex", "beagle").describe()
  • new Dog("Bo", "poodle").name
  • new Dog("Bo", "poodle") instanceof Animal
  • new Animal("Cat").describe()

Step 6 of 12Learn

The is-a test

Inheritance says something strong: every subclass instance is a fully valid instance of the superclass. A savings account is an account. A dog is an animal. Anywhere the code expects an Account, a SavingsAccount must work.

Before writing extends, say the sentence out loud: "A ___ is a ___." If it sounds wrong, or only partly right, inheritance is the wrong tool.

  • "A car is a vehicle." Inheritance can fit.
  • "A car is an engine." No. A car has an engine. That's composition: the car holds an engine object in a field.
  • "A stack is a list." Tempting, because a stack stores items in order, but a list allows inserting in the middle and a stack must not. If Stack extends Array, callers can splice into the middle and break the stack's rule.

The last case shows the main danger. A subclass inherits everything public from the parent, including methods that make no sense for it. You can't un-inherit a method; you can only override it to throw an error, which surprises every caller who trusted the parent's interface.

Two more practical warnings:

  • Keep hierarchies shallow. Three levels is often plenty. Deep chains such as Vehicle → MotorVehicle → Car → SportsCar → ConvertibleSportsCar make it hard to know where any behavior comes from.
  • Most languages allow only one superclass. Java, C#, JavaScript and Swift support single inheritance of classes, so spending that one slot carelessly is costly. Python and C++ allow multiple inheritance, which adds power and complexity.

Step 7 of 12Practice · Sort into groups

Apply the is-a test. Which relationships fit inheritance, and which are really "has-a" (composition)?

Tap an item, then tap its group (or drag it there).

Step 8 of 12Compare

is-a vs has-a

Aspectis-a: inheritancehas-a: composition
Sentence test"A savings account is an account.""A car has an engine."
Codeclass SavingsAccount extends Accountthis.engine = new Engine()
You getThe parent's entire public interfaceOnly the methods you choose to expose
CouplingTightest there isLoose: depends on public methods only

Step 9 of 12Note

Step 10 of 12Learn

Protected members and the super chain

Private fields raise a question: can a subclass see its parent's private data? In JavaScript, no. A #balance declared in Account is invisible even to SavingsAccount. The subclass must use the parent's public methods, such as deposit(), just like any other caller.

Many languages offer a middle level called protected: visible to the class and its subclasses, hidden from everyone else. Java, C# and C++ have a protected keyword. Python signals it with a single underscore by convention, and JavaScript developers sometimes do the same.

Protected access is convenient, but it is a weaker form of encapsulation. Every subclass that touches a protected field depends on it, so the parent can no longer change that field freely. Many designers keep fields private even from subclasses and offer protected or public methods instead, so the parent keeps control of its own invariants.

One more detail: constructors run from the top of the hierarchy down. Creating a SavingsAccount runs the Account constructor first (through super), then the rest of the SavingsAccount constructor. This guarantees that the parent part of the object is valid before the child adds to it.

Step 11 of 12Practice · Put in order

A class C extends B and B extends A. Each constructor calls super() first and then logs its own name. In what order are the names logged when you run new C()?

Drag the items, or use the arrow buttons, to put them in order.

  1. B
  2. C
  3. A

Step 12 of 12Practice · Choose one

A developer writes class Stack extends Array so that push and pop are inherited for free. What is the biggest design problem?