EMZETT.
Login

Inheritance

In short: A mechanism through which a class (subclass) takes over the fields and methods of another class (superclass), instead of defining them again.

In more detail: The subclass can adopt inherited methods, override them (redefine them with its own behaviour), or extend them with additional methods of its own. Via the super keyword, it can still access the superclass’s original implementation. Inheritance is one of the four core principles of OOP and the technical basis for polymorphism.

In Depth

class Vehicle {
    int speed = 0;
    void accelerate() { speed += 10; }
}
 
class Car extends Vehicle {
    // automatically inherits speed AND accelerate()
    void honk() { System.out.println("Honk!"); }   // own, additional method
}

Car gets speed and accelerate() handed to it from Vehicle, with no need to write them itself — this relationship is called an “is-a” relationship: a Car IS A Vehicle (with additional, more specific properties). That’s the most important rule of thumb for deciding whether inheritance is even appropriate: does the statement “X is a Y” really fit, or is it only being constructed to reuse code?

A subclass can override an inherited method — provide its own version with an identical signature that replaces the inherited one:

class ElectricCar extends Vehicle {
    @Override
    void accelerate() {
        speed += 20;   // electric cars accelerate faster
    }
}

Most languages only allow single inheritance (a class can inherit from only ONE superclass) — as a way around the desire for multiple “sources of behaviour”, interfaces serve this purpose, of which a class can implement several at the same time. Deep, nested inheritance hierarchies (class inherits from class inherits from class …) are today considered a design warning sign in many cases (the “fragile base class problem”) — changes to a superclass high up in the hierarchy can have unexpected side effects on all deeply nested subclasses. As an alternative, “composition over inheritance” is often recommended: achieve behaviour by composing independent objects rather than through deep class hierarchies.

See also: Classes, super Keyword, Polymorphism, OOP