Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 8

COMP1161

Introduction
to
Object-oriented Programming

Aggregation
(Based mainly on Lewis and Loftus, Java Software Solutions, Ch. 4)

Copyright © 2012 Pearson Education, Inc.


How Objects Communicate

• One object communicates with another object by invoking the other object’s
methods
• In order to do this the invoking object must have a reference to the invoked
object
• The easiest way to do this is by making the invoked object an attribute of the
invoking object.

A Java Example:
public class Person {
private Name name;
private Car familyCar;

}

• This is called aggregation

Copyright © 2012 Pearson Education, Inc.


How Objects Communicate

• The Person object can communicate with any of the two objects
A Java Example:
public class Person {

..
familyCar.setMileage(2000);
name.changeLastName(“James”);
}

Copyright © 2012 Pearson Education, Inc.


Aggregation

• Aggregation is depicted in UML as shown below:

A person has a name


A person has a car

An object of the class at the diamond end of the line holds a reference to an object
of the class at the other end of the line.
Copyright © 2012 Pearson Education, Inc.
Strong Aggregation

• Strong Aggregation (also called composition) is depicted by a


diamond that is filled in:

If the Person object is destroyed than the Name object is also destroyed.
Copyright © 2012 Pearson Education, Inc.
Weak Aggregation

• Weak Aggregation is depicted by a hollow diamond:

The Car object can exist even if the Person object is destroyed.
Copyright © 2012 Pearson Education, Inc.
Uses of Aggregation

• Aggregation is used when an object must “hold” other objects.


• For example, an object is made up of several parts
• A car has four wheels, an engine, and a body

• Aggregation is also used when two objects need to communicate.

MainMenu AddressBook

DataBase

Copyright © 2012 Pearson Education, Inc.


Association

• Aggregation is an example of an association between two classes


• There are other types of association in OOP
• For example, a dependency is where one class uses another class
without storing a reference to it
• A method parameter, or return type
• As another example, inheritance is an association between two
classes where one class gets all the attributes and methods of
another class as its own.
• More on Inheritance later

Copyright © 2012 Pearson Education, Inc.

You might also like