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
Vehiclebase class withspeedanddescribe(). MakeCarandBicyclesubclasses. - Override
describe()in each subclass to return different output - Add a third level:
SportsCar extends Carwith extra fields liketopSpeed