Bird
0
0

Given the following Java code snippet:

medium📝 Analysis Q5 of 15
LLD - Behavioral Design Patterns — Part 1
Given the following Java code snippet:
abstract class DataAnalysis {
    final void analyze() {
        collectData();
        analyzeData();
        reportResults();
    }
    abstract void analyzeData();
    void collectData() { System.out.println("Collecting data"); }
    void reportResults() { System.out.println("Reporting results"); }
}
class SalesAnalysis extends DataAnalysis {
    void analyzeData() { System.out.println("Analyzing sales data"); }
}
public class Main {
    public static void main(String[] args) {
        DataAnalysis analysis = new SalesAnalysis();
        analysis.analyze();
    }
}
What will be the output when the main method is executed?
AReporting results Collecting data Analyzing sales data
BAnalyzing sales data Collecting data Reporting results
CCollecting data Reporting results Analyzing sales data
DCollecting data Analyzing sales data Reporting results
Step-by-Step Solution
Solution:
  1. Step 1: Understand the template method

    The analyze() method is final and defines the sequence: collectData(), analyzeData(), then reportResults().
  2. Step 2: Identify overridden methods

    analyzeData() is abstract in base and implemented in SalesAnalysis to print "Analyzing sales data".
  3. Step 3: Execution flow

    Calling analysis.analyze() runs collectData() (prints "Collecting data"), then analyzeData() (prints "Analyzing sales data"), then reportResults() (prints "Reporting results").
  4. Final Answer:

    Collecting data Analyzing sales data Reporting results -> Option D
  5. Quick Check:

    Template method enforces order; overridden method runs in middle [OK]
Quick Trick: Template method fixes steps order; subclass customizes middle step [OK]
Common Mistakes:
MISTAKES
  • Assuming overridden method runs first or last
  • Ignoring the final method's fixed sequence
  • Confusing method call order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes