Monday, October 21, 2019

Association in Java Definition and Examples

Association in Java Definition and Examples 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). Association 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.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.