Page 532 - Introduction to Programming with Java: A Problem Solving Approach
P. 532
498 Chapter 12 Aggregation, Composition, and Inheritance
playAGame method. To shuffle the deck, call deck.shuffle(). To deal a card to the first player, call
player1.addCard(deck.dealCard()). How’s that for straightforward?
public void playAGame()
{
}
// end playAGame
deck.shuffle();
// Deal all the cards to the two players.
while (deck.getCurrentSize() > 0)
{
}
...
player1.addCard(deck.dealCard());
player2.addCard(deck.dealCard());
Figure 12.21 Partial implementation for Game class’s playAGame method
We’ll leave it to you to finish this program. Two end-of-chapter exercises and a project suggest various
elaborations.
Apago PDF Enhancer
12.11 Problem Solving with Association Classes (Optional)
Aggregation, composition, and inheritance implement some of the most common kinds of associations among classes and objects—a has-a association for aggregation and composition, and an is-a association for inheritance. Be aware that there are many other possible kinds of associations, which you can conjure up easily by rattling off a few verb phrases, like: “be next to. . . ,” “get. . .from. . . ,” “set. . .in. . . ,” “make. . . with. . . ,” run. . .toward. . . ,” “sell. . .to. . . ,” and so on. Typically, these other kinds of associations are more complicated than is-a or has-a associations. This section describes a powerful way to model other associations.
As you have seen, you can implement simple aggregation and composition associations by giving the container object a reference to each component object. This reference allows container object code to invoke component object methods. But for other kinds of associations, you may need multiple references and addi- tional variables and methods. In other words, you may need a separate class just to describe the association. Such a class is called an association class. An association class defines an association object that represents a relationship among other objects. An association object is like an aggregation/composition container, in that it has instance variables that refer to other objects. But it’s different in that the objects it refers to also re- fer to it, and each cannot contain the other. An association object typically receives references to the objects it associates when it is constructed. Whereas an aggregation/composition container contains its component objects, an association object just “knows about” the objects it associates.
Now let’s see how this might apply to our previous Dealership program. What we’ve done so far with that program isn’t much to brag about. We created a company with a sales manager, some sales people, and some cars. But what about customers? What about sales? Suppose we add a customer class to our Dealership