014-007-009

Final Methods and Template Method Pattern

Hard

Problem Description

Final Methods and Template Method Pattern

In this problem: You will implement the Template Method Pattern using final methods, creating an AbstractReport class whose generateReport() method cannot be overridden by subclasses.

Learning Objective: Understand the role of final methods and their relationship to the Template Method Pattern

Overview

In inheritance, adding the final modifier to a parent class method prevents subclasses from overriding it. The Template Method Pattern defines the skeleton of an algorithm in a final method and delegates individual steps to abstract methods implemented by subclasses.

Specifications

AbstractReport Class (abstract)

  • final method generateReport(): Calls 3 methods in order:
    1. collectData() - Collect data
    2. formatData() - Format data
    3. printReport() - Print report
  • Abstract methods: collectData(), formatData(), printReport()

SalesReport Class (extends AbstractReport)

  • collectData(): Prints "Collecting sales data..."
  • formatData(): Prints "Formatting sales figures..."
  • printReport(): Prints "=== Sales Report ===", "Total Sales: $50,000", "Items Sold: 1,200"

InventoryReport Class (extends AbstractReport)

  • collectData(): Prints "Scanning inventory database..."
  • formatData(): Prints "Organizing inventory items..."
  • printReport(): Prints "=== Inventory Report ===", "Total Items: 5,000", "Low Stock: 23"

Main Class

  • Create instances of SalesReport and InventoryReport
  • Call generateReport() on each
  • Print an empty line between the two reports

Output Format

Collecting sales data...
Formatting sales figures...
=== Sales Report ===
Total Sales: $50,000
Items Sold: 1,200

Scanning inventory database...
Organizing inventory items...
=== Inventory Report ===
Total Items: 5,000
Low Stock: 23

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up