How would you implement the Template Method pattern in Java?

The Template Method pattern is implemented by defining a final method in an abstract base class that fixes the sequence of steps in an algorithm, while individual steps are delegated to abstract or overridable methods that subclasses implement.

Key Points

Example

A ReportGenerator base class can define generate() as fetchData() → formatData() → exportReport(), with PdfReportGenerator and ExcelReportGenerator only overriding exportReport().

abstract class DataProcessor {

    public final void process() {
        readData();
        parseData();
        saveData();
    }

    protected abstract void readData();
    protected abstract void parseData();

    protected void saveData() {
        System.out.println("Saving processed data");
    }
}

class CsvDataProcessor extends DataProcessor {
    protected void readData() { System.out.println("Reading CSV"); }
    protected void parseData() { System.out.println("Parsing CSV"); }
}

Interview Tip

A concise interview answer is

I put the fixed algorithm sequence in a final method on an abstract base class, and expose the steps that vary as abstract methods for subclasses to implement. Making the template method final keeps subclasses from reordering or skipping steps, so the overall process stays consistent while the details change per subclass.

Last updated: 16 July 2026

Previous question: How does the Template Method pattern differ from the Strategy pattern?

Next question: Can you provide an example where you would use the Template Method pattern?

More Java Design Patterns interview questions

All Java Design Patterns questions