javablogspot

Just another WordPress.com weblog

Java Term of the Week: Association

Posted by damuchinni on March 4, 2009

Definition:
The association relationship is a way of describing that a class knows about and holds a reference to another class. This can be described as a “has-a” relationship because the typical implementation in Java is through the use of an instance field. The relationship can be bi-directional with each class holding a reference to the other. Aggregation and composition are types of association relationships.

Examples:
Imagine a simple war game where there is a AntiAircraftGun class and a Bomber class. Both classes need to be aware of each other as they are designed to destroy each other:

public class AntiAirCraftGun {

private Bomber target;
private int positionX;
private int positionY;
private int damage;

public void setTarget(Bomber newTarget)
{
this.target = newTarget;
}

//rest of AntiAircraftGun class
}

public class Bomber {

private AntiAirCraftGun target;
private int positionX;
private int positionY;
private int damage;

public void setTarget(AntiAirCraftGun newTarget)
{
this.target = newTarget;
}

//rest of Bomber class
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: