Lesson 19 / 38

Inheritance

Reuse code with extends and super, see how every class descends from Object, why Java allows only single class inheritance, and when to prefer composition.

extends and super

A subclass extends one superclass and inherits its non-private members. super(...) calls the parent constructor (first line); super.method() calls the parent version. Java has single class inheritance.

class Animal {
    Animal(String name) { /* ... */ }
    String sound() { return "..."; }
}
class Dog extends Animal {
    Dog() { super("dog"); }
    @Override String sound() { return "woof"; }
}

Prefer composition

Deep inheritance trees are brittle. Often "has-a" (hold another object as a field) is more flexible than "is-a". Reach for inheritance only for genuine subtype relationships.