Course contentsShow
← Java
Lesson 529 of 2,87012. Abstract Classes and InterfacesFree lesson

The Template Method Pattern with Abstract Classes

Using abstract classes to define algorithmic skeletons with hooks, a pattern interfaces cannot easily express.

The Template Method Pattern with Abstract Classes

You'll learn how abstract classes let you define an algorithmic skeleton with predefined steps and customizable "hooks."

What Is the Template Method Pattern?

The Template Method Pattern uses an abstract class to define the overall structure of an algorithm, while letting subclasses override specific steps. The parent class controls the flow — the "template" — and subclasses fill in the details.

Think of it like a recipe template: "Prepare ingredients, cook them, serve the dish." The parent class defines that sequence. Subclasses decide how to cook (grill versus bake) without changing the overall flow.

Why Abstract Classes?

This pattern is where abstract classes truly shine over interfaces. You need:

  1. A concrete method to define the algorithm's structure (can't be overridden)
  2. Abstract methods for required customization points
  3. Optional "hook" methods (concrete but meant to be overridden)

Interfaces can't easily express this mix before default methods, and even with them, abstract classes better communicate "this is a base for extension."

Simple Structure

abstract class RecipeTemplate {
    // Template method - defines algorithm skeleton
    public final void prepareRecipe() {
        prepareIngredients();
        cook();
        serve();
    }
    
    // Abstract step - subclasses must implement
    protected abstract void cook();
    
    // Concrete steps - shared behavior
    protected void prepareIngredients() {
        System.out.println("Gathering ingredients");
    }
    
    protected void serve() {
        System.out.println("Serving dish");
    }
}

class PastaRecipe extends RecipeTemplate {
    protected void cook() {
        System.out.println("Boiling pasta");
    }
}

The final keyword on prepareRecipe() prevents subclasses from changing the algorithm's structure — they can only customize designated steps.

Key Takeaway:
The Template Method Pattern uses abstract classes to enforce a fixed algorithm structure while allowing subclasses to customize specific steps through abstract or hook methods — a design interfaces alone cannot easily express.