What is the Template Method pattern, and how does a Java abstract class express it?
answer
- Skeleton in base, steps in subclass
- abstract method = the gap to fill
- template method often final
- Hollywood Principle: don't call us, we'll call you
- AbstractList = get + size
basics
~20 sTemplate Method is a pattern where a parent class writes the fixed steps of an algorithm in one method and leaves a few specific steps for subclasses to fill in. In Java you use an abstract class: a final/concrete method holds the skeleton and calls abstract methods the subclass must implement.
solid answer
~40 sTemplate Method defines the overall structure (the 'skeleton') of an algorithm in a base class while deferring certain steps to subclasses. In Java this is encoded with an abstract class: one concrete (often final) method runs the invariant sequence of steps and calls one or more abstract 'primitive' methods that each subclass implements. This inverts control: the base class calls the subclass ('the Hollywood principle: don't call us, we'll call you') rather than the subclass calling shared helpers. The benefit is that the algorithm's shape lives in exactly one place and cannot be reordered or skipped by subclasses, while the variable parts are pluggable. JDK examples include AbstractList, where indexed iteration and other operations are written once in terms of abstract get(int) and size().
go deeper
Can state that a parent class holds the fixed steps and subclasses fill specific gaps via abstract methods, and name AbstractList as an example.
Explains inversion of control / Hollywood Principle, why the template method is final, and distinguishes primitives from hooks.
Contrasts it with Strategy, notes the inheritance coupling cost, and explains how AbstractList reuses get/size to implement the rest of the List contract.
Discusses when to prefer composition (Strategy/functional) over an abstract-class hierarchy, the fragility of protected primitives as a published contract, and Java 8 default methods as an alternative skeleton carrier.
## The problem it solves Imagine several classes that all follow the *same sequence of steps* but differ in *how* one or two of those steps work. If each class copies the whole sequence, the shared structure is duplicated, and a fix to the sequence must be applied in many places. The **Template Method** pattern removes that duplication. ## Definitions - **Algorithm skeleton:** the fixed ordering of steps that defines *what* happens and *in what order*. - **Primitive (abstract) method:** a step the base class declares but does not implement — each subclass must supply it. - **Template method:** the single concrete method in the base class that performs the skeleton, calling the primitive methods at the right points. - **Abstract class:** in Java, a class declared `abstract` that may contain both implemented methods and unimplemented (`abstract`) methods; it cannot be instantiated directly — you must subclass it. ## How Java encodes it Java's `abstract class` is the natural home for the pattern: 1. The base class declares one **concrete** method (the template) that contains the step ordering. 2. That method calls one or more **`abstract`** methods (the primitives). Because they are `abstract`, the compiler forces every concrete subclass to implement them. 3. The template method is often marked **`final`** so subclasses cannot override (and thereby corrupt) the skeleton — they may only fill in the primitives. ## Inversion of control Normally *your* code calls library code. With Template Method it is reversed: the base class's template method calls *your* subclass's primitive. This is the **Hollywood Principle** — "Don't call us, we'll call you." The framework owns the flow; you own the gaps. ## A concrete example ```java abstract class Report { public final String build() { // template method (skeleton) return header() + body() + footer(); } protected String header() { return "=== Report ===\n"; } // default hook protected abstract String body(); // primitive — subclass must fill protected String footer() { return "\n--- end ---"; } // default hook } ``` A `SalesReport extends Report` only implements `body()`; the order header→body→footer is guaranteed. ## In the JDK The JDK's skeletal collection classes are the canonical real-world example. `AbstractList<E>` implements `iterator()`, `indexOf()`, `equals()`, `hashCode()` and more **once**, all written in terms of the two abstract primitives `get(int index)` and `size()`. To build a read-only list you extend `AbstractList`, implement just those two methods, and inherit a correct algorithm for everything else. `AbstractMap`, `AbstractSet`, and `AbstractQueue` follow the same shape. ## Why it matters Template Method gives you **code reuse without copy-paste** and **controlled extension**: the parts that must stay consistent are locked in the base class; the parts that legitimately vary are the only things a subclass can change.
- Why is the template method often declared final?So subclasses cannot override and reorder or skip the fixed steps; they may only supply the primitive methods. This protects the invariant structure of the algorithm.
- What is the difference between a primitive (abstract) method and a hook?A primitive is abstract — every subclass must implement it. A hook has a default (often empty or sensible) implementation in the base class, so overriding it is optional.
saying these in an interview costs you the question
- Saying the subclass calls the base class's shared steps — it's the reverse; the base class calls the subclass.
- Confusing Template Method (compile-time, inheritance) with Strategy (run-time, composition).
- Claiming an interface alone implements Template Method — you need a concrete method holding the skeleton, so an abstract class (or a default method) is required.