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
}

Leave a comment