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:
Get hands-on with 1400+ tech skills courses.