Java Reference
In-Depth Information
them. If you can't find the object in the bag, you can't remove it, and you just say so. Finally, the
last remove operation simply empties the bag of all objects.
1.4
How many cans of dog food did you buy? Did you remember to get anchovy paste? Just what is in
that bag? The answers to these questions can be answered by the following operations:
Count the number of times a certain object occurs in the bag
Test whether the bag contains a particular object
Look at all objects that are in the bag
We have enough behaviors for now. At this point, we would have written all 10 behaviors on a
piece of paper or on the class-responsibility-collaboration (CRC) card pictured in Figure 1-1, as
suggested in Appendix D.
FIGURE 1-1
A CRC card for a class Bag
Bag
Responsibilities
Get the number of items currently in the bag
See whether the bag is full
See whether the bag is empty
Add a given object to the bag
Remove an unspeciied object from the bag
Remove an occurrence of a particular object from
the bag, if possible
Remove all objects from the bag
Count the number of times a certain object occurs in the bag
Test whether the bag contains a particular object
Look at all objects that are in the bag
Collaborations
The class of objects that the bag can contain
1.5
Since a bag is an abstract data type, we only describe its data and specify its operations. We do not indicate
how to store the data or how to implement its operations. Don't think about arrays, for example. You first
need to clearly know what the bag operations do: Focus on what the operations do, not on how they do
them. That is, you need a detailed set of specifications before you can use a bag in a program. In fact, you
should specify the bag operations before you even decide on a programming language.
Note: Since an abstract data type, or ADT, describes a data organization independently of a
programming language, you have a choice of programming languages for its implementation.
Specifying a Bag
Before we can implement a bag in Java, we need to describe its data and specify in detail the meth-
ods that correspond to the bag's behaviors. We'll name the methods, choose their parameters,
decide their return types, and write comments to fully describe their effect on the bag's data. Our
eventual goal, of course, is to write a Java header and comments for each method, but first we will
express the methods in pseudocode and then in Unified Modeling Language (UML) notation.
VideoNote
Designing an ADT
 
 
 
Search WWH ::




Custom Search