Quick revision
The short answer
In the template method pattern, a base class defines the steps of an algorithm in one method and lets subclasses override specific steps. AbstractList implements most List methods in terms of get and size, which subclasses supply, and HttpServlet.service dispatches to doGet, doPost and the others that servlets override. Spring's JdbcTemplate keeps the same idea of fixed steps, getting a connection, translating exceptions and releasing resources, but takes the variable step as a callback such as RowMapper, using composition instead of inheritance; and when subclasses must not change the order of steps, the template method is marked final.
What to remember
In this answer, we saw that the template method pattern fixes an algorithm's outline in a base class and lets subclasses override specific steps. AbstractList builds a full List from get and size, and HttpServlet.service dispatches to doGet, doPost and the rest. JdbcTemplate keeps the fixed steps of JDBC work but takes the varying step as a callback such as RowMapper, which is composition instead of inheritance, and a template method should be final when subclasses must not change the order of steps.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
In the template method pattern, a base class defines the steps of an algorithm in one method and lets subclasses override specific steps. AbstractList implements most List methods in terms of get and size, which subclasses supply, and HttpServlet.service dispatches to doGet, doPost and the others that servlets override. Spring's JdbcTemplate keeps the same idea of fixed steps, getting a connection, translating exceptions and releasing resources, but takes the variable step as a callback such as RowMapper, using composition instead of inheritance; and when subclasses must not change the order of steps, the template method is marked final.
Why this question is asked
Template method is the pattern behind every framework class we extend and then fill in, and behind most of the classes in Spring whose names end in Template. Understanding it explains why we write doGet instead of service, why a custom List needs only two methods, and why JdbcTemplate exists at all. Interviewers ask it with JdbcTemplate because the comparison shows whether we understand the trade-off between inheritance and composition. In this answer, we will recap the pattern with a small example, look at AbstractList and HttpServlet, see how JdbcTemplate turns the same idea into callbacks, and discuss when to make the template method final.
1A Quick Recap of Template Method
Some algorithms have a fixed outline with one or two steps that vary. Generating a report always means loading data, formatting it and writing it out, but the formatting differs for CSV and PDF. The template method pattern puts the outline in a method of an abstract base class, the template method, which calls abstract or overridable methods, often called hook methods, for the varying steps. Subclasses fill in the hooks and inherit the outline.
The benefit is that the fixed part is written once, and the order of steps is guaranteed. The base class calls the subclass, not the other way round, which is sometimes called the Hollywood principle: do not call us, we will call you.
- generate(sales) in the base classFixed outline, final
- Call header()Overridden: sku,qty
- Call format(sales)Subclass step: CSV rows
- Call write(...)Fixed step, private
4 steps in order. Play them, or step through them one at a time.
Notice the two kinds of hooks. format is abstract, so every subclass must provide it. header has a default, so subclasses override it only if they want a header. The template method generate is final, so no subclass can skip writing or reorder the steps.
2AbstractList: A Whole Interface From Two Methods
java.util.AbstractList is a template method class on a large scale. The List interface has dozens of methods, but AbstractList implements almost all of them, including iterator(), indexOf(), contains(), equals(), hashCode() and subList(), in terms of two abstract steps: get(int) and size(). A read-only list needs only those two. To make it modifiable, a subclass also overrides set, and add and remove for a resizable list; otherwise those methods throw UnsupportedOperationException.
Every method we did not write is a template method that calls our get and size. The same idea appears in AbstractMap, which builds a Map from entrySet(), and in InputStream, whose read(byte[], int, int) is written in terms of the single-byte read() a subclass must implement.
3HttpServlet: Dispatching to doGet and doPost
In the Servlet API, the container calls service(request, response) for each request. HttpServlet implements service as a template method: it reads the HTTP method and calls doGet, doPost, doPut, doDelete and so on. It also handles details we rarely think about, such as conditional GET with getLastModified, and answering HEAD and OPTIONS. The default doGet and doPost reply with a 405 Method Not Allowed (or 400 for older protocol versions), so a servlet only overrides the methods it supports.
This is why overriding service directly is a mistake in most servlets: it replaces the dispatching outline and loses the HEAD, OPTIONS and 405 behaviour the template provided.
4JdbcTemplate: The Same Idea Through Callbacks
Plain JDBC code always repeats the same steps: get a connection, create a statement, set parameters, execute, loop over the result set, map rows, close everything in the right order even on errors, and turn SQLException into something meaningful. Only two parts vary: the SQL with its parameters and the way a row becomes an object.
JdbcTemplate keeps the fixed steps in its own methods, just like a template method, but it does not ask us to subclass it. Instead, we pass the varying step as an object, a callback, such as a RowMapper. That is composition: JdbcTemplate holds the algorithm, and we lend it the one piece it needs.
| Aspect | Template method (inheritance) | JdbcTemplate style (callback) |
|---|---|---|
| How the varying step is given | Override a hook in a subclass | Pass an object or lambda |
| Instances | One subclass per variation | One shared template, many callbacks |
| Coupling | Subclass depends on base internals | Only on the callback interface |
| Examples | AbstractList, HttpServlet | JdbcTemplate, TransactionTemplate |
Composition has clear advantages here. A lambda is much shorter than a subclass. One JdbcTemplate bean can be shared by the whole application, and each query passes a different callback. Callbacks can be reused and tested on their own, and we are free to extend another class. The same callback style appears in TransactionTemplate, RestTemplate and the newer JdbcClient and RestClient fluent APIs. So JdbcTemplate is often described as the template method idea implemented with the strategy pattern.
5When to Make the Template Method Final
If subclasses are meant to fill in steps but not to change the outline, the template method should be final. Otherwise a subclass can override generate and skip a step, such as writing an audit line or releasing a resource, and the guarantee the base class was designed to give disappears. Making it final turns that guarantee into something the compiler enforces. The hooks themselves should be protected, not public, because they are not meant to be called from outside, and private helpers like write should stay private.
The JDK does not always do this, for historical reasons: HttpServlet.service is not final, which is why overriding it remains possible. In our own base classes we have the choice, and final is the safe default.
6Follow-up questions
What are the downsides of template method?
Subclasses depend on the base class's internal call order and on which hooks it calls when, so changing the base class can break them, the fragile base class problem. Each variation needs a subclass, and Java's single inheritance means a class can only use one such template. That is why callback templates are often preferred for new designs.
How is template method different from strategy?
Template method varies part of an algorithm through inheritance: the subclass is the variation. Strategy varies a whole algorithm or a step through composition: we pass an object. JdbcTemplate sits between them, a fixed outline with strategy objects for the steps.
Are there template methods in Spring outside the Template classes?
Yes. AbstractRoutingDataSource asks subclasses for determineCurrentLookupKey(), and OncePerRequestFilter implements doFilter and asks subclasses for doFilterInternal(). Both define the outline and leave one step to us.
7Conclusion
In this answer, we saw that the template method pattern fixes an algorithm's outline in a base class and lets subclasses override specific steps. AbstractList builds a full List from get and size, and HttpServlet.service dispatches to doGet, doPost and the rest. JdbcTemplate keeps the fixed steps of JDBC work but takes the varying step as a callback such as RowMapper, which is composition instead of inheritance, and a template method should be final when subclasses must not change the order of steps.
Open with
The template method pattern puts the outline of an algorithm in one method of a base class, and that method calls hook methods that subclasses override for the parts that vary.
Then, if they want more
The base class controls the order, and subclasses only fill in steps. A good JDK example is AbstractList. If I implement just get and size, I get iterator, contains, indexOf, equals, hashCode, subList and toString for free, because they are all written in terms of those two methods.
In the Servlet API, HttpServlet.service is a template method: it looks at the HTTP method and calls doGet, doPost and so on, and the defaults return 405, so my servlet only overrides what it supports. That is also why we should not override service itself. JdbcTemplate relates to the same idea but implements it with composition.
The fixed steps of JDBC, getting a connection, creating the statement, iterating the result set, closing everything and translating SQLException into a DataAccessException, live inside JdbcTemplate. The variable step, like mapping a row to an object, I pass in as a callback such as a RowMapper lambda.
So I do not subclass anything, one JdbcTemplate bean is shared by the whole application, and callbacks can be reused and tested separately. When I write my own template method, I make it final if subclasses must not reorder or skip steps, and I keep the hooks protected.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Explain the template method pattern and give examples from the JDK and the Servlet API....": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/aaaa91a117/