Lesson 21 / 38

Abstract Classes & Interfaces

Choose between abstract classes and interfaces, mix in behaviour with default methods, and model capabilities like Comparable and Runnable.

When to use which

An interface is a pure contract — a type can implement many. An abstract class can hold state and shared code but a class extends only one. Rule of thumb: interface for capability (Comparable, Runnable), abstract class for a partial base implementation.

Interface with default

Since Java 8 an interface can provide default method bodies, so adding a method doesn't break existing implementers.

interface Shape {
    double area();
    default String describe() {
        return "area = " + area();
    }
}
class Circle implements Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}

static and private interface methods

Since Java 8, interfaces can have static methods (called on the interface itself, e.g. Shape.unitCircle()). Since Java 9, private methods let default methods share helper code without exposing it to implementers.

interface Shape {
    double area();

    static Shape unitCircle() { return new Circle(1); }

    private String label() { return "Shape["; }
    default String describe() { return label() + area() + "]"; }
}