Page 512 - Introduction to Programming with Java: A Problem Solving Approach
P. 512
478 Chapter 12 Aggregation, Composition, and Inheritance
/*******************************************************
*
DealershipDriver.java
Dean & Dean
This class demonstrates car dealership composition.
*******************************************************/
*
*
*
public class DealershipDriver
{
public static void main(String[] args)
{
Manager ryne = new Manager("Ryne Mendez");
SalesPerson nicole = new SalesPerson("Nicole Betz");
SalesPerson vince = new SalesPerson("Vince Sola");
Dealership dealership =
new Dealership("OK Used Cars", ryne); ⎫
dealership.addPerson(nicole); ⎪⎬⎪ dealership.addPerson(vince); ⎭ dealership.addCar(new Car("GMC")); ⎫ dealership.addCar(new Car("Yugo")); ⎬ dealership.addCar(new Car("Dodge"));⎭ dealership.printStatus();
}
// end DealershipDriver class
}
// end main
Apago PDF Enhancer
Output:
For aggregations, pass in copies of references.
For compositions, create anonymous objects.
OK Used Cars
Nicole Betz
Vince Sola
GMC
Yugo
Dodge
Ryne Mendez
Figure 12.7 Driver for Dealership program
Here’s the general rule for implementing aggregation relationships. Whenever two classes have an ag- gregation relationship, you should save the contained class’s object in a reference variable in the containing class, and you should also save it in another reference variable outside of the containing class. That way, the object can be added to another aggregation and have two different “owners” (having two different owners is allowed by aggregation). Putting this in the context of the Dealership program, DealershipDriver uses local variables when it instantiates Manager and SalesPerson objects. That enables Manager and SalesPerson objects to exist independently from the dealership, and that mirrors the real world.
Now let’s look at the general rule for implementing composition relationships. Whenever two classes have a composition relationship, you should save the contained class’s object in a reference variable in the containing class, and you should not save it elsewhere. That way, the object can have only one “owner” (having just one owner is required by composition). Putting this in the context of the Dealership program,