Completing the Definition of the Class Coin
Let's enhance the simpler class Coin1 to get the class Coin.
We'll cover the following...
Often a good problem-solving strategy is to solve a somewhat simpler problem that we can enhance to solve the original problem. Recall that we defined the class Coin1
as a step towards the class Coin
. The previous lesson shows the definition of this simpler class.
Revising the constructor
We decided in the previous lesson to have Coin1
’s default constructor create a heads-up coin. Now let’s change that constructor so that new coins will be either heads or tails at random. To do that, we
could have the constructor call the public method toss
, but as we noted earlier in this chapter, calling a public method from within a constructor should be avoided for now. We can, however, define a private method getToss
that does what toss
did, and call it from both the constructor and toss
, as follows:
// Returns a random value of either HEADS or TAILS.private CoinSide getToss(){CoinSide result = CoinSide.TAILS;if (Math.random() < 0.5)result = CoinSide.HEADS;return result;} // End getToss// Call getToss from the constructor:public Coin(. . .){. . .sideUp = getToss();} // End constructor// Call getToss from the public method toss:public void toss(){sideUp = getToss();} // End toss
The data fields value
and year
Our original design calls for two more data fields to represent the coin’s value and its mint year. We now want to add these fields to our enhanced ...