Difference Between Aggregation and Composition in JavaAn object is a real-time entry, and objects have relationships between them both in programming or real life. Objects are related to each other using more than one relationship, such as Aggregation, Composition, Association, etc. Let's understand the difference between Aggregation and Composition but before that we understand all these three relationships in detail. CompositionComposition is a "belong-to" type of relationship in which one object is logically related with other objects. It is also referred to as "has-a" relationship. We can understand has-a or belong-to by using the following example: A classroom belongs to a school, or we can say a school has a classroom. So, calling both of them is only a matter of point of view. Composition is a strong type of "has-a" relationship because the containing object is its owner. So, objects are tightly coupled, which means if we delete the parent object, the child object will also get deleted with it. Let's take an example to understand how we can implement the logic for the Composition relationship in Java: CompositionExample.java Output: AggregationAggregation relationship is also a "has-a" relationship. The only difference between Aggregation and Composition is that in Aggregation, objects are not tightly coupled or don't involve owning. All the objects are independent of each other and can exist even if the parent object gets deleted. Let's understand this by using the following example: A car comes with a wheel, and if we take off its wheels, the wheels will still exist. But a car without wheels won't be as useful as a car with its wheels, and that's how this relationship existed in the first place for assembling the parts to a bigger construct, which is capable of more things than its parts. Let's take an example to understand how we can implement the logic for the Aggregation relationship in Java: Address.java AggregationExample.java Output: AssociationAssociation is not a has-a relationship and the weakest relationship among all. In an Association relationship, none of the objects are parts or members of another. A simple example of Association is a mother and her child. Let's take an example to understand how we can implement the logic for Association relationships in Java: AssociationExample.java Output: Difference Between Aggregation and CompositionLet's understand the differences between Aggregation and Composition:
Next TopicMorris Traversal for Inorder in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India