Aggregation vs Composition vs Association vs Direct Association

steven0529 picture steven0529 · Feb 23, 2014 · Viewed 56.5k times · Source

I am reviewing my knowledge in object-oriented programming. Under the relationship between classes topic, I have encountered some relationships which are a bit ambiguous to me.

I know dependency "uses-a" and inheritance "is-a" but I'm a bit unfamiliar with Aggregation, Composition, Association and Direct Association; also, which of them is "has-a" relationship. Some use Aggregation interchangeably with Association.

What is Direct Association? Also, what is Composition? In UML diagrams, the arrows that represents them are different. I would be really thankful if you could clear these things out for me.

Answer

bvdb picture bvdb · Oct 27, 2014

Please note that there are different interpretations of the "association" definitions. My views below are heavily based on what you would read in Oracle Certification books and study guides.

Temporary association

A usage inside a method, its signature or as a return value. It's not really a reference to a specific object.

Example: I park my Car in a Garage.

Temporary Association UML

Composition association

A so-called "STRONG relationship": The instantiation of the linked object is often hard coded inside the constructor of the object. It cannot be set from outside the object. (Composition cannot be a many-to-many relationship.)

Example: A House is composed of Stones.

Composition UML

Direct association

This is a "WEAK relationships". The objects can live independent and there are usually setters or other ways to inject the dependent objects.

Example: A Car can have Passengers.

Direct Association UML

Aggregation association

Very similar to a Direct association. It's also a "WEAK relationship" with independent objects. However here the associated objects are a crucial part of the containing object.

Example: A Car should have Tires.

Aggregation UML

Note: Both Direct associations and Aggregation associations are often generalized as "Associations". The difference is rather subtle.