How do abstract classes enable the Template Method pattern, and why is a concrete method calling an abstract one the core mechanism?
answer
- base = fixed skeleton in concrete method
- abstract methods = varying steps
- template method usually final
- dynamic dispatch routes to subclass
- Hollywood Principle / inversion of control
- AbstractList over get + size
basics
~20 sThe abstract class writes the overall algorithm once in a concrete method, but leaves the varying steps as abstract methods it calls. Subclasses fill in only those steps. The base controls the order and structure; subclasses control the details.
solid answer
~50 sIn the Template Method pattern, an abstract base class defines a concrete 'template' method that lays out the fixed skeleton of an algorithm — the sequence of steps — and within it calls one or more abstract (or overridable 'hook') methods representing the steps that vary. The template method is typically made `final` so subclasses can't alter the structure, only the steps. Subclasses extend the base and implement the abstract steps; at runtime, dynamic dispatch routes the base's calls to the subclass's implementations. This inverts control: the framework (base) calls your code (subclass), not the other way around — the Hollywood Principle. It centralizes the shared algorithm in one place, eliminates duplication across subclasses, and constrains them to vary only at the designated extension points. The JDK uses this in skeletal implementations like AbstractList, where iteration and bulk operations are written once on top of the abstract get(int) and size().
go deeper
Recognizes the shape: base method calls steps subclasses fill in; can name the pattern.
Explains the concrete-calls-abstract mechanism and dynamic dispatch routing to the subclass override.
Articulates final-template enforcement, hooks vs primitives, JDK skeletal implementations, and the inversion-of-control framing.
Weighs inheritance coupling and single-inheritance limits against a Strategy/composition refactor, addresses construction-order hazards, and reasons about evolving such a base in a public API.
## The problem it solves Suppose several classes all perform the *same overall procedure* but differ in a few steps. For example, 'process a data file' always means: open it, read records in a loop, transform each record, write the result, close it — but *how* a record is transformed differs per file type. If you copy that whole procedure into each subclass, you duplicate the structure (open/loop/close) and risk the copies drifting apart. The **Template Method** pattern fixes this. ## The structure An **abstract class** provides: 1. A **concrete template method** — an ordinary method *with a body* that codes the fixed skeleton: the steps and their order. 2. One or more **abstract methods** (the *primitive operations* or *hooks*) representing the steps that vary. The template method **calls these abstract methods**. Subclasses implement only the abstract steps. They never see or rewrite the skeleton. ```java abstract class ReportGenerator { // template method: the fixed algorithm (often final) public final String generate() { String header = buildHeader(); // varies String body = buildBody(); // varies return decorate(header + body); // shared concrete step } protected abstract String buildHeader(); protected abstract String buildBody(); private String decorate(String s) { return "<<" + s + ">>"; } } ``` ## Why 'concrete calls abstract' is the heart of it The magic is **dynamic dispatch** (also called late binding). When the concrete `generate()` calls `buildHeader()`, Java does *not* resolve that call to the base class's version (there is none — it's abstract). At runtime it dispatches to the **actual subclass's** override, based on the object's real type. So the base class, written once and knowing nothing about any specific subclass, ends up running subclass-specific code at exactly the right points in the algorithm. This is **inversion of control**: normally *your* code calls *library* code. Here the abstract base (the 'framework') calls *your* subclass code. This is nicknamed the **Hollywood Principle** — 'don't call us, we'll call you.' ## Making the template method final The template method is usually declared **`final`**. This prevents subclasses from overriding the *skeleton itself* — they may only customize the designated abstract steps, not reorder or replace the algorithm. This enforces the invariant structure while still allowing variation, a deliberate design constraint. ## Hooks vs primitive operations Two kinds of customization points: - **Primitive operations** — abstract methods the subclass *must* implement (the required steps). - **Hooks** — concrete methods in the base with a default (often empty) implementation that subclasses *may* override to inject optional behavior. Because they have a default, overriding is optional. ## JDK examples (skeletal implementations) The JDK's `Abstract*` collection classes are textbook Template Method. `AbstractList` implements `iterator()`, `indexOf()`, `equals()`, `hashCode()`, and bulk operations *once*, all written in terms of the two abstract primitives `get(int)` and `size()`. To build a read-only list you implement just those two and inherit everything else — the algorithms are templated on your primitives. `AbstractMap`, `AbstractSet`, and `InputStream` (whose concrete `read(byte[])` calls the abstract `read()`) follow the same shape. ## Trade-offs The pattern couples subclasses tightly to the base class's structure and is limited by single inheritance (a subclass can extend only one such base). It also exposes the construction-order hazard: a template method must not be invoked from the constructor, or it would call subclass hooks before subclass fields are initialized. Modern alternatives push the varying steps in as **strategy objects** (composition + functional interfaces) instead of subclassing, trading the inheritance coupling for an extra object.
- Why is the template method usually declared final?To lock the algorithm's structure. Subclasses are meant to customize only the designated abstract steps, not reorder or replace the whole procedure. Making it final prevents accidental or intentional override of the skeleton, preserving the invariant the pattern guarantees.
- How does Template Method differ from the Strategy pattern?Template Method varies steps via inheritance and overriding, fixed at compile time and bound to one base class. Strategy varies behavior via composition — you inject a strategy object (often a lambda/functional interface) at runtime and can swap it. Strategy avoids inheritance coupling and the single-inheritance limit.
- What's a 'hook' versus a 'primitive operation' in this pattern?A primitive operation is an abstract method the subclass must implement (a required step). A hook is a concrete method with a default (often empty) body the subclass may optionally override to inject extra behavior at a known point in the algorithm.
saying these in an interview costs you the question
- Letting subclasses override the template method itself (it should be final to protect the skeleton).
- Confusing Template Method (compile-time, inheritance) with Strategy (runtime, composition).
- Calling the template method from the constructor — it invokes subclass hooks before subclass init.
- Thinking the base must know about its subclasses — it doesn't; dynamic dispatch handles routing.