Java Reference
In-Depth Information
coins = new Bag<Coin>();
} // end default constructor
public boolean add(Coin aCoin)
{
return coins.add(aCoin);
} // end add
public Coin remove()
{
return coins.remove();
} // end remove
public boolean isEmpty()
{
return coins.isEmpty();
} // end isEmpty
} // end PiggyBank
1.18
Listing 1-4 provides a brief demonstration of the class PiggyBank . The program adds some coins to
the bank and then removes all of them. Since the program does not keep a record of the coins it
adds to the bank, it has no control over which coins are removed. Although the output indicates that
the coins leave the bank in the opposite order from how they entered it, that order depends on the
bag's implementation. We'll consider these implementations in the next chapters.
Notice that, in addition to the main method, the program defines another method, addCoin .
Since main is static and calls addCoin , it must be static as well. The method addCoin accepts as its
arguments a Coin object and a PiggyBank object. The method then adds the coin to the bank.
LISTING 1-4
A demonstration of the class PiggyBank
/**
A class that demonstrates the class PiggyBank.
@author Frank M. Carrano
*/
public class PiggyBankExample
{
public static void main(String[] args)
{
PiggyBank myBank = new PiggyBank();
addCoin( new Coin(1, 2010), myBank);
addCoin( new Coin(5, 2011), myBank);
addCoin( new Coin(10, 2000), myBank);
addCoin( new Coin(25, 2012), myBank);
Search WWH ::




Custom Search