Difference Between Association, Composition and Aggregation in Java | Code Factory
Reference Link : Link
Donate : Link
In Object-oriented programming, one object is related to other to use functionality and service provided by that object. This relationship between two objects is known as the Association
.
Both Composition
and Aggregation
are the form of Association
between two objects.
We refer association between two objects as Composition
, when one class owns other class and other class can not meaningfully exist, when it's owner destroyed, for example, Human class is a composition of several body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist meaningfully, this is one example of Composition.
Another example of Composition
is Car and it's part e.g. engines, wheels etc. Individual parts of the car can not function when a car is destroyed. While in the case of Aggregation
, including object can exists without being part of the main object e.g. a Player which is part of a Team, can exist without a team and can become part of other teams as well. Another example of Aggregation
is Student in School class, when School closed, Student still exist and then can join another School.
The Composition
is stronger than Aggregation
. In Short, a relationship between two objects is referred as an Association
, and an Association
is known as Composition
when one object owns other while an Association
is known as Aggregation
when one object uses another object.
To understand difference between Composition
and Aggregation
in software design is "part-of
" and "has
". If one object is part-of another object e.g. Engine is part of Car, then Association
or Relationship
between them is Composition
. On the other hand, if one object just has another object e.g. Car has the driver then it's Aggregation
.