A Problem Solved: Representing Coins
In this lesson, we solve a problem using enumeration.
We'll cover the following
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 tailsname
—the coin’s name as a stringvalue
—a representation of the coin’s valueyear
—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 up;
otherwise, returns "TAILS". */
public String getSideUp()
/** Returns the coin's name as a string. */
public String getName()
/** Returns the value of the coin in cents. */
public int getValue()
/** Returns the coin’s mint year as an integer. */
public int getYear()
/** Returns true if the coin is heads side up. */
public boolean isHeads()
/** Returns true if the coin is tails side up. */
public boolean isTails()
/** Tosses the coin (sets sideUp randomly to one of two values). */
public void toss()
/** Returns the coin as a string in the form coin-name/year/side-up. */
public String toString()
Notice that we have not specified any set methods. Thus, once we create a Coin
object, its value and mint date cannot be altered, just like a real coin. The method getSideUp
could have returned the value of the third field sideUp
, but instead, we chose to have it return a string. We did this so that the data type we eventually choose for sideUp
will not be a part of the method’s specification and, in fact, will be hidden from the client.
Get hands-on with 1400+ tech skills courses.