Java Reference
In-Depth Information
System.out.println("Removing all the coins:");
int amountRemoved = 0;
while (!myBank.isEmpty())
{
Coin removedCoin = myBank.remove();
System.out.println("Removed a " + removedCoin.getCoinName() +
".");
amountRemoved = amountRemoved + removedCoin.getValue();
} // end while
System.out.println("All done. Removed " + amountRemoved +
" cents.");
} // end main
private static void addCoin(Coin aCoin, PiggyBank aBank)
{
if (aBank.add(aCoin))
System.out.println("Added a " + aCoin.getCoinName() + ".");
else
System.out.println("Tried to add a " + aCoin.getCoinName() +
", but couldn't");
} // end addCoin
} // end PiggyBankExample
Output
Added a PENNY.
Added a NICKEL.
Added a DIME.
Added a QUARTER.
Removing all the coins:
Removed a QUARTER.
Removed a DIME.
Removed a NICKEL.
Removed a PENNY.
All done. Removed 41 cents.
Note: A method can change the state of an object passed to it as an argument
You pass two arguments to the method addCoin : a coin and a piggy bank. Both of these argu-
ments are references to objects that exist in the main method. The method addCoin stores copies
of these references in its parameters, which, as you will recall, behave as local variables.
Although addCoin cannot change the references, because they exist in the main method, it can
alter the state of the referenced objects. In particular, it changes the piggy bank —that is, the
PiggyBank object —by adding coins to it. That bank, remember, is local to main and is out-
side of addCoin .
 
Search WWH ::




Custom Search