Skip to content

Chapter 11 of 37

Inheritance

Apply single, multilevel, and hierarchical inheritance while favoring composition.

36 minutes 10 quick checksBy Subha Prasad
Lesson 11 of 37Course navigation

Lesson content

Read, practise, then check your understanding

A class has one direct superclass, establishing single inheritance. A subclass can itself be extended, producing multilevel inheritance; several subclasses of one base form a hierarchy. Java avoids multiple class inheritance but allows multiple interfaces.

Specialization

abstract class Shape {
    abstract double area();
}

final class Rectangle extends Shape {
    private final double width, height;
    Rectangle(double width, double height) {
        this.width = width; this.height = height;
    }
    @Override double area() { return width * height; }
}

super accesses superclass construction or behavior. Constructors are not inherited; private members remain private. An override must honor the base contract and may widen visibility, narrow checked exceptions, and return a covariant reference type. Use final to close a class or method when extension would break invariants. Prefer composition when the relationship is “has-a,” behavior changes independently, or a hierarchy exists only to reuse code.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes extends?
Which Java term matches this description: The keyword establishing a class's single direct superclass.
Which statement best describes single inheritance?
Which Java term matches this description: One class directly extending one superclass.
Which statement best describes multilevel inheritance?
Which Java term matches this description: A chain in which a derived class is extended again.
Which statement best describes hierarchical inheritance?
Which Java term matches this description: Multiple classes independently extending one superclass.
Which statement best describes composition?
Which Java term matches this description: Building behavior from contained collaborators instead of an is-a hierarchy.

0 of 10 checks passed

Your progress is saved on this device.