All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Back to results for “OOP”
Java › Interfaces & Abstract Classes

How would you use an abstract class to implement the Template Method pattern, defining a fixed algorithm skeleton with some steps left abstract for subclasses to fill in?

Intermediate

Answer

An abstract class is particularly well-suited to the Template Method pattern (already covered in the design patterns topic) because, unlike an interface, it can provide a concrete, non-overridable (final) method defining the overall algorithm's fixed sequence, while declaring specific customization points as abstract methods that subclasses must implement -- an interface alone (even with default methods) can't achieve quite the same guarantee, since a default method CAN be overridden by an implementing class, potentially altering the intended algorithm sequence in a way a final template method in an abstract class specifically prevents.
public abstract class ReportGenerator {
    public final void generate() {  // fixed algorithm, cannot be overridden since it's final
        String data = fetchData();
        String formatted = formatData(data);
        saveReport(formatted);
    }
    protected abstract String fetchData();      // subclasses MUST implement
    protected abstract String formatData(String data);  // subclasses MUST implement
    protected void saveReport(String content) { System.out.println("Saving: " + content); }  // shared default behavior
}
Real-world example A reporting framework's abstract ReportGenerator class guarantees every report subtype follows the identical fetch-format-save sequence via a final generate() method, with individual report types (PdfReportGenerator, CsvReportGenerator) only needing to implement the specific fetchData() and formatData() steps relevant to their format, unable to accidentally alter the guaranteed overall sequence.

Common follow-ups: Why couldn't this exact same guarantee be achieved using an interface with default methods instead of an abstract class?;What's the risk of NOT marking the template method as final, even in an abstract class?