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

                500 Chapter 12 Aggregation, Composition, and Inheritance
 // This class associates SalesPerson2, Car, and Customer classes
public class Sale
{
 private Car car; ⎫ private SalesPerson2 salesperson; ⎬ private Customer customer; ⎭ private double price;
...
//***************************************************************
public Sale(Car car, SalesPerson2 person,⎫ ⎬
      {
Customer customer, double price) ⎭ this.car = car;
this.salesperson = person;
this.customer = customer;
this.price = price;
...
// end constructor
}
...
references to classes being associated
 references passed into constructor
            Apago PDF Enhancer
Figure 12.23 Partial implementation of Sale class shown in Figure 12.22
Caveat—Don’t Try to Inherit from an Association Participant
You might be tempted to try to use inheritance to create an association class, because you might think that would give you “free access” to at least one of the participants in the association. Don’t try to do that. All you’d get would be the ability to make an enhanced clone of one of the objects you want to associate, and you’d have to copy all the details between the clone and the real thing—a waste of effort. Treat an association like an aggregation, with references to the participating objects passed into the association constructor.
Summary
• Object-oriented languages help you organize things and concepts into two basic kinds of hierarchies—a has-a hierarchy for components in an aggregation or composition, and an is-a hierarchy for types in an inheritance.
• An aggregation or composition hierarchy exists when one large object contains several smaller (compo- nent) objects.
• For a given whole-part class relationship, if the container contains the only reference to a component, the component association is composition. Otherwise, it’s aggregation.
• In an inheritance hierarchy, subclasses inherit all the variables and methods of the superclasses above them, and they typically add more variables and methods to what they inherit.
 






































































   532   533   534   535   536