Abstract Classes

OOP · lesson 7 of 43 · 3 min read

When to use an abstract class, and how the template method pattern fixes the steps of an algorithm.

Open this lesson in the learning hub

Key points

  • An abstract class cannot be instantiated. It exists to be extended and to hold whatever subclasses share.
  • An abstract method has no body. Every concrete subclass must implement it or the code will not compile.
  • Reach for it when subclasses share real state and real code. An interface cannot hold mutable instance fields.
  • Template method lives here: a final method fixes the order of steps, abstract methods fill them in.
  • If there is no shared state, prefer an interface. A class has one parent but can implement many interfaces.

Example

public class Main {
    static abstract class Report {
        // Template method: the shape is fixed, the steps are not.
        final void print() {
            System.out.println("=== " + title() + " ===");
            body();
            System.out.println("--- end ---");
        }

        abstract String title();      // no body: subclasses must supply one
        abstract void body();

        String footer() { return "generated"; }   // shared concrete helper
    }

    static class SalesReport extends Report {
        @Override String title() { return "Sales"; }
        @Override void body()   { System.out.println("Q3 revenue: 1,240,000 (" + footer() + ")"); }
    }

    public static void main(String[] args) {
        new SalesReport().print();

        // Report r = new Report(); // will not compile: abstract
        Report adhoc = new Report() {            // anonymous subclass
            @Override String title() { return "Ad hoc"; }
            @Override void body()   { System.out.println("nothing to report"); }
        };
        adhoc.print();
    }
}

Abstract class for shared state and code; interface for a shared capability.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.