018-001-007

Interface and Abstract Class Cooperation

Hard

Problem Description

Interface and abstract class Cooperation

In this problem, you will create a program that implements a three-layer structure using the Printable interface, abstract class Document, and concrete classes Invoice/Receipt, displaying formatted strings to standard output via each class's print() method.

Learning Objective: Understand the three-layer design pattern where an interface defines a contract, an abstract class provides shared implementation, and concrete classes provide specific implementations

Overview

Define a contract for output using the Printable interface, provide common processing (title management) in an abstract Document class, and create concrete classes Invoice and Receipt that print in individual formats.

Specifications

Printable interface

  • Declare void print() method

Document class (abstract, implements Printable)

  • Has a protected String title field
  • constructor Document(String title) sets the title
  • public String getTitle() method returns the title
  • Does not implement print() (remains abstract)

Invoice class (extends Document)

  • Has a private int amount field
  • Constructor Invoice(String title, int amount) initializes both fields
  • print() method outputs in the format "[Invoice] {title}: ${amount}"

Receipt class (extends Document)

  • Has a private String item field
  • Constructor Receipt(String title, String item) initializes both fields
  • print() method outputs in the format "[Receipt] {title}: {item}"

Main class

  1. Create Invoice("Order-001", 5000) and call print()
  2. Create Receipt("Purchase-001", "Laptop") and call print()
  3. Call getTitle() on both objects and print in the format "Titles: Order-001, Purchase-001"

Output Format

[Invoice] Order-001: $5000
[Receipt] Purchase-001: Laptop
Titles: Order-001, Purchase-001

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