0Pricing
Java Academy · Lesson

Template Method: Defining Algorithm Skeletons

Define the skeleton of an algorithm in a base class and let subclasses fill in the steps.

Template Method: Defining Algorithm Skeletons is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Template Method Intent

Template Method defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. Subclasses can override steps without changing the overall structure.

The Abstract Base Class

The base class has the template method (usually final) that orchestrates the steps. Abstract methods represent the varying steps. Concrete methods provide default behavior.

public abstract class DataProcessor {
    // Template method — final, defines the algorithm
    public final void process() {
        readData();
        processData();
        writeResult();
    }
    protected abstract void readData();
    protected abstract void processData();
    protected void writeResult() {
        System.out.println("Result written (default)");
    }
}

Concrete Subclasses

Each subclass fills in the abstract steps. The template method's sequence never changes — only the implementation of individual steps varies.

public class CSVProcessor extends DataProcessor {
    protected void readData()    { System.out.println("Reading CSV..."); }
    protected void processData() { System.out.println("Parsing CSV rows..."); }
}
public class XMLProcessor extends DataProcessor {
    protected void readData()    { System.out.println("Reading XML..."); }
    protected void processData() { System.out.println("Parsing XML nodes..."); }
    @Override
    protected void writeResult() { System.out.println("Writing XML result."); }
}

Hook Methods

A hook is an optional step with a default (often empty) implementation. Subclasses can override hooks to add optional behavior without being forced to implement it.

public abstract class Game {
    public final void play() {
        initialize();
        while (!isDone()) takeTurn();
        printWinner();
    }
    protected void initialize() {}  // hook — optional override
    protected abstract boolean isDone();
    protected abstract void takeTurn();
    protected abstract void printWinner();
}

Template Method vs Strategy

Template Method uses inheritance: the skeleton is fixed in the base class, steps overridden in subclasses. Strategy uses composition: the whole algorithm is external. Strategy is more flexible; Template Method is simpler when steps share a lot of context.

Java InputStream as Template Method

java.io.InputStream's read(byte[], int, int) is implemented in terms of the abstract read(). Subclasses implement the one-byte version; the multi-byte read is the template.

Template Method for Report Generation

Define a report template: gather data, format it, and output it. Swap subclasses for PDF, HTML, or CSV output without changing the orchestration logic.

public abstract class ReportGenerator {
    public final String generate() {
        List<Record> data = fetchData();
        String body = format(data);
        return wrap(body);
    }
    protected abstract List<Record> fetchData();
    protected abstract String format(List<Record> data);
    protected String wrap(String body) { return body; } // hook
}

Preventing Override of the Template

Declare the template method final to prevent subclasses from altering the algorithm structure. Only the hook and abstract methods should be overridable.

public final void process() {
    validate(); // abstract
    execute();  // abstract
    cleanup();  // hook with default
}

Abstract vs Concrete Steps

Make a step abstract when it must be provided by the subclass. Make it concrete (possibly empty) when subclasses may override it for customization.

Template Method in JUnit

JUnit 4's setUp() and tearDown() are hooks in the template method defined by the test runner. The runner controls when they are called.

Template Method in Spring

Spring's JdbcTemplate uses Template Method internally. The template controls connection, statement creation, and cleanup; you supply a RowMapper lambda for the varying "map row" step.

List<User> users = jdbcTemplate.query(
    "SELECT * FROM users",
    (rs, row) -> new User(rs.getLong("id"), rs.getString("name"))
);

Avoid Deep Inheritance

Template Method relies on inheritance, which can produce deep class hierarchies. Limit to 1-2 levels. If subclasses start overriding many steps differently, consider switching to Strategy.

Quick Check

What keyword prevents subclasses from changing the template method's sequence?

Recap

Template Method locks the algorithm skeleton in a base class with final. Subclasses implement abstract steps and optionally override hooks. Keep hierarchies shallow; use Strategy when more flexibility is needed.

Frequently asked questions

Is the “Template Method: Defining Algorithm Skeletons” lesson free?

Yes — the full text of “Template Method: Defining Algorithm Skeletons” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Template Method: Defining Algorithm Skeletons”?

Define the skeleton of an algorithm in a base class and let subclasses fill in the steps. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Template Method: Defining Algorithm Skeletons” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Observer Pattern: Event Notification
  2. Strategy Pattern: Interchangeable Algorithms
  3. Command Pattern: Encapsulating Actions
  4. Template Method: Defining Algorithm Skeletons
← Back to Java Academy