Association

Connecting Java classes

The association relationship indicates that a class knows about, and holds a reference to, another class. Associations 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.

Example

Imagine a simple war game with an AntiAircraftGun class and a Bomber class. Both classes need to be aware of each other because 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.

Format
mla apa chicago
Your Citation
Leahy, Paul. "Association." ThoughtCo, Jan. 16, 2017, thoughtco.com/association-2034002. Leahy, Paul. (2017, January 16). Association. Retrieved from https://www.thoughtco.com/association-2034002 Leahy, Paul. "Association." ThoughtCo. https://www.thoughtco.com/association-2034002 (accessed April 25, 2018).