OOP - Association

When writing a program, variables that hold value types are created on the stack.

Variables that hold object types, create the object on the heap, and a reference to the objects is stored in the variable on the stack.

When we create an instance of the class, and call the constructor...

ClassName ObjectName = new ClassName();

...the constructor first creates the object on the heap, then sets the initial values of any fields in the object. If successful, it returns the reference to the object to the variable.

Classes, however, do not exist in our programs independently.

Association defines a relationship between different objects that allows one object to perform an action on another’s behalf. This is called delegation.

One object ‘has a’ relationship with another object.
These relationships are implemented through references to other objects.

We already know that an object can have fields that store simple values (our atomic data types).

Objects can also have fields that hold references to other objects. You should never hold copies of data from other objects, only references to them.

For example a car has an engine, which is also an object.

There are two types of association that we need to concern ourselves with:

    • Association Aggregation

    • Association Composition

Association Aggregation

Aggregation is where an object has a reference to another object. That object though may exist separately from the related object.
For example a football team may contain a player, but that player could move to another team.
When an object which contains other objects is destroyed, the other objects will still exist.

Association Composition

Composition is where an object has a reference to another object that is wholly and exclusively owned and used by its ‘parent’ object.
For example a hotel is made up of rooms. The rooms cannot exist outside of the hotel.
When an object that contains other objects is destroyed; then the objects will no longer exist.

Key Terms

Delegate

To pass on responsibility for an action to another object.