Java Reference
In-Depth Information
In the software world, we define an aggregate object as any object that contains
references to other objects as instance data. For example, an Account object con-
tains, among other things, a String object that represents the name of the account
owner. We sometimes forget that strings are objects, but technically that makes
each Account object an aggregate object.
Aggregation is a special type of dependency. That is, a class that is defined in
part by another class is dependent on that class. The methods of the aggregate
object generally invoke the methods of the objects from which it is composed.
Let's consider another example. The program StudentBody shown in Listing 7.5
creates two Student objects. Each Student object is composed, in part, of two
Address objects, one for the student's address at school and another for the stu-
dent's home address. The main method does nothing more than create the Student
objects and print them out. Once again we are passing objects to the println
method, relying on the automatic call to the toString method to create a valid
representation of the object that is suitable for printing.
The Student class shown in Listing 7.6 represents a single student. This class
would have to be greatly expanded if it were to represent all aspects of a student.
We deliberately keep it simple for now so that the object aggregation is clearly
shown. The instance data of the Student class includes two references to Address
objects. We refer to those objects in the toString method as we create a string
representation of the student. By concatenating an Address object to another
string, the toString method in Address is automatically invoked.
LISTING 7.5
//********************************************************************
// StudentBody.java Author: Lewis/Loftus
//
// Demonstrates the use of an aggregate class.
//********************************************************************
public class StudentBody
{
//-----------------------------------------------------------------
// Creates some Address and Student objects and prints them.
//-----------------------------------------------------------------
public static void main (String[] args)
{
Address school = new Address ("800 Lancaster Ave.", "Villanova",
"PA", 19085);
Address jHome = new Address ("21 Jump Street", "Lynchburg",
"VA", 24551);
 
Search WWH ::




Custom Search