skip to content

Template Method in Java

Template Method in the JDK is the skeletal AbstractList/AbstractMap family: the algorithm is fixed in the abstract class and a few primitive methods are left to subclasses. Interviewers ask how few methods you must implement to get a working List.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What is the Template Method pattern, and how does a Java abstract class express it?

level: juniorimportance: must knowfreq 70%

answer

  1. Skeleton in base, steps in subclass
  2. abstract method = the gap to fill
  3. template method often final
  4. Hollywood Principle: don't call us, we'll call you
  5. AbstractList = get + size

basics

~20 s

Template 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 s

Template 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

for a junior

Can state that a parent class holds the fixed steps and subclasses fill specific gaps via abstract methods, and name AbstractList as an example.

for a middle

Explains inversion of control / Hollywood Principle, why the template method is final, and distinguishes primitives from hooks.

for a senior

Contrasts it with Strategy, notes the inheritance coupling cost, and explains how AbstractList reuses get/size to implement the rest of the List contract.

for a principal

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.

context

open as a page

How does AbstractList use Template Method, and what does a minimal immutable List subclass look like?

level: middleimportance: should knowfreq 55%

basics

~20 s

AbstractList already writes most of the List methods (iterator, indexOf, equals, etc.) using two abstract steps you provide: get(index) and size(). To make a read-only list you extend AbstractList and implement just those two methods.

open as a page

What is the difference between an abstract primitive method and a hook method in Template Method, and how does the JDK use each?

level: middleimportance: should knowfreq 45%

basics

~20 s

A primitive is an abstract step the subclass must implement. A hook is a step with a default body in the base class, so overriding it is optional. The template method calls both; hooks let subclasses tweak behavior without being forced to.

open as a page

How does Template Method differ from the Strategy pattern, and when would you choose composition over an abstract-class hierarchy?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Template Method varies steps using inheritance: a subclass overrides abstract methods, fixed at compile time. Strategy varies behavior using composition: you pass in an object (or lambda) that can change at run time. Prefer Strategy when you need flexibility or want to avoid deep class hierarchies.

open as a page

What are the design pitfalls of Template Method, and how do calling overridable methods from a constructor or self-use affect a Java abstract-class skeleton?

level: principalimportance: should knowfreq 35%

basics

~20 s

Template Method ties subclasses tightly to the base class, so base changes can break them. A key Java trap: if a constructor (or initializer) calls an overridable method, the subclass's override runs before the subclass's own fields are initialized, leading to bugs. The skeleton's protected methods become a contract you must document and keep stable.

open as a page