Friday, December 27, 2019
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.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment