What is the Template Method pattern?
Why Interviewers Ask This
This question targets practical, hands-on experience with OOP Concepts. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
The Template Method pattern defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. The base class controls the overall structure (the "template") while subclasses override specific steps without changing the overall algorithm structure. Example — data processing pipeline: abstract class DataProcessor { // Template method -- defines the algorithm structure: public final void process() { readData(); validateData(); processData(); formatOutput(); saveResults(); } // Steps that subclasses must implement: protected abstract void readData(); protected abstract void processData(); // Steps with default implementation (can be overridden): protected void validateData() { System.out.println("Default validation: checking for null"); } protected void formatOutput() { System.out.println("Default formatting: plain text"); } protected void saveResults() { System.out.println("Default: saving to file"); } } class CSVDataProcessor extends DataProcessor { @Override protected void readData() { System.out.println("Reading CSV file"); } @Override protected void processData() { System.out.println("Parsing CSV columns"); } @Override protected void formatOutput() { System.out.println("Formatting as JSON"); // Override default } } class APIDataProcessor extends DataProcessor { @Override protected void readData() { System.out.println("Calling REST API"); } @Override protected void processData() { System.out.println("Deserializing JSON response"); } } // Both use the same algorithm structure: new CSVDataProcessor().process(); new APIDataProcessor().process();. Hook methods: optional override points — base class provides empty implementation: protected void postProcess() {} // Hook -- override if needed. Real examples: JUnit TestCase (setUp, test, tearDown), Java's AbstractList, Spring's JdbcTemplate. vs Strategy: Template Method uses inheritance to vary part of algorithm; Strategy uses composition to vary the whole algorithm.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your OOP Concepts experience.