014-004-007
Protected and Template Method
Hard
Problem Description
Protected and Template method
In this problem, you will create a program that implements the Template method pattern by overriding protected methods to generate two types of reports — SalesReport and InventoryReport — and displays the result to standard output.
Learning Objective: Understand the basics of the Template Method pattern using the protected modifier
Overview
Define a superclass Report with a public method generate() and protected methods formatHeader() and formatBody(). Subclasses SalesReport and InventoryReport override the protected methods to generate different reports.
Input
- Line 1: sales amount (integer)
- Line 2: item count (integer)
Specifications
Report class
- Define
public void generate()method- Calls
formatHeader()and prints its return value - Calls
formatBody()and prints its return value
- Calls
- Define
protected String formatHeader()method that returns"=== Report ===" - Define
protected String formatBody()method that returns"No data"
SalesReport class (extends Report)
- Accept sales amount (integer) in constructor
- Override
formatHeader()to return"=== Sales Report ===" - Override
formatBody()to return"Total sales: $" + salesAmount
InventoryReport class (extends Report)
- Accept item count (integer) in constructor
- Override
formatHeader()to return"=== Inventory Report ===" - Override
formatBody()to return"Items in stock: " + itemCount
Main class
- Read sales amount and item count using
Scanner - Create a
SalesReportinstance and callgenerate() - Create an
InventoryReportinstance and callgenerate()
Output Format
=== Sales Report ===
Total sales: $<salesAmount>
=== Inventory Report ===
Items in stock: <itemCount>
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