Module 3 · Lesson 2

Inheritance

Build new classes on top of existing ones. Learn base/derived classes, super, and method overriding.

Audio: Inheritance
0:000:00

Inheritance

Inheritance lets a class build on top of another class. Instead of repeating fields and methods, you say "this class is a kind of that class" and automatically pick up everything the parent already has.

Why Inheritance?

When two classes share most of their behavior, copying the code into both is fragile — fix a bug in one, forget the other. Inheritance solves this by letting the child class reuse the parent class and only specify what's different.

A common rule of thumb: use inheritance for "is-a" relationships. A Dog is an Animal. A SavingsAccount is a BankAccount. If the relationship is "has-a" (a Car has an Engine), use composition instead.

Base and Derived Classes

The class being extended is the base (or parent, or superclass). The class doing the extending is the derived (or child, or subclass).

Syntax varies by language:

  • Python: class Dog(Animal):
  • JavaScript / Java: class Dog extends Animal
  • C++: class Dog : public Animal

The child gets all public/protected fields and methods of the parent automatically.

Calling the Parent with super

When the child needs to add to what the parent does (rather than replace it), it can call the parent's version using super(). This is most common in constructors — the child constructor usually calls the parent constructor first to initialize inherited fields, then adds its own.

Method Overriding

A child class can override a parent method by defining a method with the same name. When you call the method on a child instance, the child's version runs. This is how a Dog can speak differently from a generic Animal.

In C++, you mark methods virtual so they can be overridden polymorphically. In Java, you add the @Override annotation to make intent explicit.

Try It Yourself

  • Create a Vehicle base class with speed and describe(). Make Car and Bicycle subclasses.
  • Override describe() in each subclass to return different output
  • Add a third level: SportsCar extends Car with extra fields like topSpeed

Code Playground

Edit the code below and click Run to see the output. Switch between languages using the tabs.

Loading editor...

Enjoying the lesson? Unlock the full Object-Oriented Design from $4.99/mo.

See plans →