Tuesday, March 12, 2013

Association Relationship

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 compositionare 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
 } 
The AntiAirCraftGun class has-a Bomber object and the Bomber class has-a AntiAirCraftGun object.