Page 530 - Introduction to Programming with Java: A Problem Solving Approach
P. 530

                496 Chapter 12 Aggregation, Composition, and Inheritance
of the two relationships. See Figure 12.18’s Deck class, which implements the Deck-GroupOfCards re-
lationship with inheritance.
   public class Deck extends GroupOfCards
  {
public static final int TOTAL_CARDS = 52;
public Deck()
{
for (int i=0; i<TOTAL_CARDS; i++)
 }
// end class Deck
...
{
}
addCard(new Card((2 + i%13), i/13));
This implements inheritance.
 With inheritance, there’s no need to prefix the method call with an object reference.
  } // end constructor
Figure 12.18 Inheritance implementation for the Deck class
Also see Figure 12.19’s alternative Deck class, which implements the Deck-GroupOfCards
Apago PDF Enhancer
relationship with composition. We feel that Figure 12.18’s inheritance code is more elegant than Fig- ure 12.19’s composition code. It has one less line, which is a good thing, but more importantly, it isn’t cluttered with references to a groupOfCards variable. In the composition code, you’re required to (1) declare a groupOfCards variable, (2) instantiate the groupOfCards variable, and (3) prefix the
 public class Deck
  {
public static final int TOTAL_CARDS = 52;
private GroupOfCards groupOfCards;
public Deck()
  {
groupOfCards = new GroupOfCards();
for (int i=0; i<TOTAL_CARDS; i++)
{
groupOfCards.addCard(new Card((2 + i%13), i/13));
 }
// end class Deck
...
}
With composition, declaring a GroupOfCards variable and instantiating it are required.
  }
// end constructor
With composition, you must prefix the method call with an object reference.
 Figure 12.19 Composition implementation for the Deck class


























































   528   529   530   531   532