Template Method Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Template Method Pattern runs in O(1) time and O(1) space, in Java as in every other language.
- ✓The classical home of the pattern: an abstract class with a concrete template method, abstract steps and optional hooks with default implementations.
- ✓Make the template method final and the steps protected abstract, which is the shape Effective Java Item 19 recommends alongside its broader advice to design and document for inheritance or else prohibit it.
- ✓The Java trap: Calling an overridable method from a CONSTRUCTOR is the classic Java failure and it appears naturally in this pattern.
- ✓Each step is a virtual call. The JIT devirtualises and inlines when only one implementation has been loaded, which is common in practice, so a template method with a single subclass often costs nothing at all; loading a second implementation triggers deoptimisation and the call site becomes bimorphic.
What Template Method Pattern actually is
Template Method Pattern in Java: what you actually reach for
Java implementation
abstract class Importer<T> {
// final: subclasses fill in steps, they do not reorder the algorithm.
public final int run(String path) {
String raw = read(path);
java.util.List<T> rows = transform(raw);
after(rows);
return rows.size();
}
protected abstract String read(String path);
protected abstract java.util.List<T> transform(String raw);
protected void after(java.util.List<T> rows) { } // optional hook
}
class CsvImporter extends Importer<String> {
private final String separator;
CsvImporter(String separator) {
this.separator = separator;
// Calling run() HERE would invoke transform() before 'separator' is set
// in a subclass: Effective Java Item 19: never call an overridable
// method from a constructor.
}
protected String read(String path) { return "a,b\nc,d"; }
protected java.util.List<String> transform(String raw) {
return java.util.List.of(raw.split(separator));
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Template Method Pattern?
The classical home of the pattern: an abstract class with a concrete template method, abstract steps and optional hooks with default implementations. Marking the template method final prevents subclasses from replacing it, which is the enforcement most other languages here cannot offer. The JDK is full of examples, including AbstractList, where implementing get and size yields a working list, and InputStream, where a single read method drives the rest.
What is the most common Java mistake when implementing Template Method Pattern?
Calling an overridable method from a CONSTRUCTOR is the classic Java failure and it appears naturally in this pattern. The superclass constructor runs before the subclass field initialisers, so an overridden step invoked from the base constructor executes against a subclass whose fields are all still at their default values, and it reads null or zero for fields that appear initialised in the source. Effective Java Item 19 calls this out explicitly, and the fix is that constructors must never call an overridable method.
How does Template Method Pattern actually perform in Java?
Each step is a virtual call. The JIT devirtualises and inlines when only one implementation has been loaded, which is common in practice, so a template method with a single subclass often costs nothing at all; loading a second implementation triggers deoptimisation and the call site becomes bimorphic. A final template method can be inlined confidently, which is a small additional argument for marking it so. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.