Association

Connecting Java classes

Program code, HTML and JavaScript on LCD screen
Dominik Pabis/Getty Images

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.

Associations join one or more of one thing against one or more of another thing. A professor might be associated with a college course (a one-to-one relationship) but also with each student in her class (a one-to-many relationship). The students in one section might be associated with the students in another section of the same course (a many-to-many relationship) while all the sections of the course relate to a single course (a many-to-one relationship).

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.