Inheritance and polymorphism

Intermediate

Introduction

Many things in a program are kinds of something more general: circles and squares are shapes, savings and current accounts are accounts. Inheritance lets a class build on another, reusing its fields and methods and changing what differs. Polymorphism then lets code work with the general kind, a Shape, while each object behaves as what it really is.

How it works

A subclass names its superclass with extends. It inherits the superclass's fields and methods, and can add its own:

class Circle extends Shape {
    private final double r;
    Circle(double r) {
        super("circle");  // the superclass's constructor runs first
        this.r = r;
    }
}

A subclass constructor must call super(...) as its first statement, unless the superclass has a constructor with no parameters, which Java then calls automatically. Private fields of the superclass exist in the object but are reachable only through the superclass's methods; protected fields can be used by subclasses too.

A subclass overrides a method by declaring one with the same name and parameters. The @Override annotation asks javac to check that a method really is being replaced, which catches misspelt names. Inside the override, super.describe() calls the parent's version. Overrides cannot narrow access: a public method stays public.

An abstract class cannot be created with new. It can declare abstract methods, with no body, that every concrete subclass must implement, and ordinary methods that use them: describe() calls area(), and each shape supplies its own area.

Polymorphism is the payoff: a variable of type Shape can hold a Circle, a Rect or a Square, and s.area() runs the version belonging to the object's actual class. This is decided while the program runs, so one loop over a Shape[] handles every kind.

To ask what an object really is, use instanceof. Since Java 16, a pattern both tests and casts: if (s instanceof Rect r) gives a variable r of type Rect inside the if. Every class ultimately extends Object, which is where toString, equals and hashCode come from. A class marked final cannot be extended.

Example

// Inheritance: an abstract base class, subclasses that override, super, and instanceof.
abstract class Shape {
    private final String name;

    Shape(String name) {
        this.name = name;
    }

    abstract double area(); // every subclass must provide this

    String describe() {
        return name + String.format(" with area %.2f", area());
    }
}

class Circle extends Shape {
    private final double r;

    Circle(double r) {
        super("circle");
        this.r = r;
    }

    @Override
    double area() {
        return Math.PI * r * r;
    }
}

class Rect extends Shape {
    protected final double w, h;

    Rect(double w, double h) {
        this("rectangle", w, h);
    }

    protected Rect(String name, double w, double h) {
        super(name);
        this.w = w;
        this.h = h;
    }

    @Override
    double area() {
        return w * h;
    }
}

class Square extends Rect {
    Square(double side) {
        super("square", side, side);
    }

    @Override
    String describe() {
        return "a " + super.describe();
    }
}

public class Main {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Rect(2, 3), new Square(2) };
        for (Shape s : shapes) System.out.println(s.describe());
        Shape s = shapes[2];
        if (s instanceof Rect r) System.out.println("a rectangle " + r.w + " by " + r.h);
        System.out.println(s instanceof Square ? "it is a square" : "not a square");
    }
}
Open in compiler

Line by line

  1. Shape is abstract: it stores the name and declares area() without a body.
  2. Circle and Rect call super with their names and override area.
  3. Square extends Rect, passing its side twice, and overrides describe to add "a " before the parent's text.
  4. The loop calls describe on each element; each object uses its own area.
  5. The pattern s instanceof Rect r matches the square, because a Square is a Rect.

Expected result

circle with area 3.14
rectangle with area 6.00
a square with area 4.00
a rectangle 2.0 by 2.0
it is a square

In the real world

Frameworks give you abstract classes and interfaces to extend: a servlet in a web server, an activity in Android, a test case in JUnit. Polymorphism is how plug-in systems work: the framework calls handle() or draw() and your subclass decides what happens. Deep inheritance trees are discouraged today in favour of interfaces and small classes combined together.

Common mistakes

  • Forgetting super(...) when the superclass has no constructor without parameters.
  • Misspelling an overriding method, which creates a new method instead; @Override catches it.
  • Using instanceof chains instead of overriding a method, which defeats polymorphism.
  • Building deep hierarchies where a change at the top breaks every subclass.

Best practices

  • Write @Override on every overriding method.
  • Use inheritance only for real "is a" relationships, and keep hierarchies shallow.
  • Put shared behaviour in the abstract superclass, and only the differences in subclasses.

Summary

extends creates a subclass that inherits from its superclass; super(...) runs the parent's constructor and super.method() its version of a method. Overrides marked @Override replace behaviour, abstract classes force subclasses to provide methods, polymorphism runs each object's own version through a superclass reference, and instanceof patterns test and cast in one step.

Quick check

1. What must a subclass constructor do first when the superclass has only a constructor with parameters?
2. What does @Override do?
3. Shape s = new Circle(1); s.area() runs which version?
4. Can you write new Shape("x") if Shape is abstract?

Key takeaways

  • extends inherits members; a subclass constructor must call super(...) first.
  • @Override marks a replaced method; the object's real class decides which version runs.
  • Abstract classes share code and force subclasses to fill in the abstract methods.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.