Page 510 - Introduction to Programming with Java: A Problem Solving Approach
P. 510
476 Chapter 12 Aggregation, Composition, and Inheritance
inside of the Dealership class. Those instance variable declarations implement the concept of the dealer- ship class containing the other three classes. The general rule is that whenever you have a class that contains another class, declare an instance variable inside the containing class such that the instance variable holds a reference to one or more of the contained class’s objects.
Also in the Dealership class, note the use of ArrayLists for the people and cars instance variables. Typically, if you have a class in a UML class diagram with a * multiplicity value, you should use an ArrayList to implement the reference to the asterisked class. ArrayLists are good for implement- ing * multiplicity values because they can expand to accommodate any number of elements.
Peruse the Car, Manager, and SalesPerson classes in Figures 12.4, 12.5, and 12.6. They simply store and retrieve data. Note the SalesPerson’s sales instance variable—it keeps track of the total sales for a sales person for the current year. There are no methods for accessing or updating the sales in- stance variable. We omitted those methods to avoid code clutter and to maintain focus on the matter at hand, aggregation and composition. In an actual car dealership program, you’d need to provide those methods.
/********************************
*
Car.java
Dean & Dean
This class implements a car.
********************************/
*
*
*
public class Car
{
Apago PDF Enhancer
private String make;
//****************************
public Car(String make)
}
// end Car class
{
}
this.make = make;
//****************************
public String getMake()
{
}
return make;
Figure 12.4
Car class for Dealership program
See the car dealership program’s driver class in Figure 12.7. Most of the code is straightforward. The main method instantiates a Manager object, two SalesPerson objects, and a Dealership object. Then main adds salesPerson and Car objects to the Dealership object. The part of main that mer- its further attention is the use of local variables for the Manager and SalesPerson objects and the use of anonymous objects for the Car objects. Why the discrepancy? Because Manager and SalesPerson relate to the Dealership class with aggregation, and Car relates to the Dealership class with composition.