Search⌘ K

A Problem Solved: Representing Coins

Explore how to design a Java class representing coins, including fields for side, name, value, and year. Learn to implement methods like toss, isHeads, isTails, and toString to simulate coin behavior and access coin data.

Problem statement

Imagine that we need to represent coins in various programs. A coin has two sides, heads and tails. Additionally, a coin has a monetary value and shows the year in which it was minted. Let’s decide that these characteristics are sufficient for our purposes and create a class of coins.

Designing the class

We’ll name the class Coin and give it four data fields, as follows:

  • sideUp—a designation for heads or tails
  • name—the coin’s name as a string
  • value—a representation of the coin’s value
  • year—a positive integer denoting the year the coin was minted

Let’s also give the class the following methods:

  • Accessor methods that return the coin’s visible side—heads or tails—its name, its value in cents, and its mint year
  • Boolean-valued methods that test whether the coin’s visible side is heads or tails
  • A method that simulates a coin toss by assigning a designation for heads or tails to sideUp at random
  • The method toString

After naming these methods and refining their specifications, we can write the following comments and method headers:

/** Returns the string "HEADS" if the coin is heads side
...