![]() |
VOOZH | about |
In object-oriented programming, relationships between classes play a crucial role in defining how objects interact with each other. Java, being an object-oriented language, provides mechanisms to model these relationships through association, aggregation, and composition.
👁 Association, Aggregation, and Composition
Association is a relationship between two independent classes where one object uses or interacts with another object. Both objects can exist independently of each other.
Example:
Ridhi belongs to bank ICICI Vijay belongs to bank ICICI
Explanation: In the above example, two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, So, it is a one-to-many relationship.
Aggregation is a special form of Association that represents a Has-A relationship with weak ownership. The contained object can exist independently of the container object.
Example:
Total students in institute: 4
It represents a Has-A relationship. In the above example: Student Has-A name. Student Has-A ID. Department Has-A Students as depicted from the below media.
Note: Code reuse is best achieved by aggregation.
Composition is a strong form of Aggregation that represents a Part-Of relationship. In Composition, the lifecycle of the contained object depends completely on the container object.
Example:
Total Rooms: 4 Room names: - Living Room - Bedroom - Kitchen - Bathroom
Explanation: In the above example, if the house is destroyed, its room also get destroyed this represents a complete composition relationship, where the room is the part of the house and the life cycle of room completely depends on the house.
Difference Between Association, Aggregation and Composition
Feature | Association | Aggregation | Composition |
|---|---|---|---|
Definition | General relationship between two classes | A special form of association with a "has-a" relationship | A stronger form of association with a "part-of" relationship |
Dependency | Classes are related but can exist independently | Contained objects can exist independently of the container object | Contained objects cannot exist without the container object |
Lifecycle | Independent lifecycles | Independent lifecycles | Dependent lifecycles |
Ownership | No ownership implied | Shared ownership | Exclusive ownership |
Strength | Weak | Moderate | Strong |
Cardinality | One-to-one, one-to-many, many-to-one, many-to-many | One-to-one, one-to-many, many-to-one, many-to-many | One-to-one, one-to-many |
Example | Teacher and Student | Library and Books | Car and Engine |
Representation | Uses a direct reference | Uses a reference to the contained object(s) | Contains instances of the contained object(s) |
Illustrative Example Code | java class | java class | java class |