Java Reference
In-Depth Information
}
// end main
}
// end OnlineShopper
Output
Sunflower seeds $12.95
Bird bath $44.99
Squirrel guard $15.47
Bird feeder
$20.50
Total cost:
$93.91
To keep the example simple, we create an array of
Item
objects to represent the choices made by the
shopper. The class
Item
, which is available to you in this topic's online resources, defines data fields for an
item's description and price, accessor methods for these fields, and the method
toString
.
Initially, we create an empty bag for
Item
objects by using
Bag
's default constructor. Notice that the
data type of
shoppingCart
is
BagInterface<Item>
. This declaration obliges
shoppingCart
to receive
only calls to methods declared in
BagInterface
. Moreover, we could replace the class
Bag
with another
class that also implements
BagInterface
without modifying the subsequent statements in the program.
Notice the loop that adds the chosen items to the bag and the loop that removes them one at a
time during checkout.
Question 7
In the previous example, a
while
loop executes during the checkout process
until the bag is empty. What
for
statement could replace the
while
statement? Use only the
existence of
shoppingCart
, not the array
items
.
1.17
Example: A piggy bank.
You might have a piggy bank, jar, or some other receptacle to hold your
spare coins. The piggy bank holds the coins but gives them no other organization. And certainly the
bank can contain duplicate coins. A piggy bank is like a bag, but it is simpler, as it has only three
operations: You can add a coin to the bank, remove one (you shake the bank, so you have no control
over what coin falls out), or see whether the bank is empty.
Assuming that we have the class
Coin
to represent coins, we can create the class
PiggyBank
given in Listing 1-3. A
PiggyBank
object stores its coins in a bag, that is, in an instance of a class
that implements the interface
BagInterface
. The
add
,
remove
, and
isEmpty
methods of
PiggyBank
each call the respective bag method to achieve their results. The class
PiggyBank
is an example of
an adapter class. See Appendix C for more on adapter classes.
LISTING 1-3
A class of piggy banks
/**
A class that implements a piggy bank by using a bag.
@author Frank M. Carrano
*/
public class
PiggyBank
{
private
BagInterface<Coin> coins;
public
PiggyBank()
{