Next Previous Up Top


4 Class Relationships

4.2 Association


4.2 Association


Association is the most straightforward way of relating classes. A class can declare a variable of some other class as part of its own representation, allowing the public methods of an object of this other class to be called. This relationship can be seen as has-a, as an object of one class 'has a' (reference to an) object of another class.

For example, using the Stack class introduced in Chapter 3, we can define a new class that uses a stack as part of its own representation:

class StackUser
{
	public int doSomething()
	{
		...
	}
	private Stack data ;
}

Each object of the class StackUser has its own private Stack object to use as it pleases.

A variation on the association relationship is where an object obtains a reference to another object via a method argument, for example:

class StackUser
{
	public int doSomething(Stack data)
	{
		...
	}
}

The called method, doSomething, and indeed any methods called from this one if the object reference is passed as a parameter, can use this parameter object in effectively the same way as if the reference was part of the representation -- but only whilst dealing with that method call, of course.


Copyright 1997 Russel Winder and Graham Roberts

Last updated: 6 Oct 1997