Thursday, September 16, 2021

Difference between Association, Composition and Aggregation in Java, UML and Object Oriented Programming

In Object-oriented programming, one object is related to another to use functionality and service provided by that object. This relationship between two objects is known as the association in object-oriented general software design and is depicted by an arrow in Unified Modelling Language or UML. Both Composition and Aggregation are the forms of association between two objects, but there is a subtle difference between composition and aggregation, which is also reflected by their UML notation. We refer to the association between two objects as Composition when one class owns other classes and other classes can not meaningfully exist, when the owner is destroyed.

For example, Human class is a composition of several body parts including the Hand, Leg, and Heart. When a human object dies, all its body parts ceased to exist meaningfully, this is one example of Composition.

Programmers often confuse between Association, Composition, and Aggregation in Object-oriented design discussions, this confusion also makes the difference between Association, Composition, and Aggregation one of the popular questions in Java Interviews, only after the difference between abstract class and interface.

Another example of Composition is Car and its 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 objects that can exist without being part of the main object like 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 exists and then can join another School or so.  In UML notation, a composition is denoted by a filled diamond, while aggregation is denoted by an empty diamond, which shows their obvious difference in terms of the strength of the relationship.

The composition is stronger than Aggregation.  In Short, a relationship between two objects is referred to as an association, and an association is known as composition when one object owns another while an association is known as aggregation when one object uses another object.

In this OOPS tutorial, we will see a couple of more examples to understand the difference between Association, Composition, and Aggregation better.

Btw, if you are new to the world of object-oriented programming and design then I also suggest you go through a hands-on course like UML and Object-Oriented Design Foundations Course by Karlovy Neisztor on Udemy. It's a great course to understand the complete process of object-oriented analysis and design for creating quality software.




An Example of Association, Composition, and Aggregation in Java

Here is an example of composition and aggregation, in terms of Java Code. By looking at this code, you can gauge the differences between these two. By the way, Composition is also very much preferred in object-oriented design over inheritance, even Joshua Bloch has stated its importance in the classic book, Effective Java.

1. Composition: 

Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes.

public class Car {
    //final will make sure engine is initialized
    private final Engine engine;  
       
    public Car(){
       engine  = new Engine();
    }
}

class Engine {
    private String type;
}


2. Aggregation: 

Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes

public class Organization {
    private List employees;
}

public class Person {
    private String name;   
}




UML Diagram of Association, Composition, and Aggregation

UML has different notations to denote aggregation, composition, and association.  Association is denoted by the simple arrow while aggregation is denoted by an empty diamond-head arrow and composition is denoted by a filled diamond-head arrow.

When you draw a UML diagram for two related classes A and B, where A is associated with B then it's denoted by A -> B. A similar way is used to show aggregation and composition between two classes.

Here are UML notations for a different kind of dependency between the two classes.

Difference between Association, Aggregation and Composition


As I said all three denotes relationship between objects and only differ in their strength, you can also view them as below, where composition represents the strongest form of relationship and association being the most general form.

Association vs Aggregation vs Composition



Association vs Composition vs Aggregation

Here is the list of differences between Composition and Aggregation in point format, for quick review. As I said the key difference between them comes from the point that in the case of Composition, One object is OWNER of another object, while in the case of aggregation, one object is just a USER or another object.

1) If A and B two classes are related to each other such that, B ceased to exist when A is destroyed, then the association between two objects is known as Composition. An example is Car and Engine. While if A and B are associated with each other, such that B can exist without being associated with A, then this association is known as Aggregation.

See Head First Object-Oriented Analysis and Design for more examples of Composition and Association in OOP.

Composition vs Association vs Aggregation in Java



2) In the case of Composition A owns B e.g. Person is the owner of his Hand, Mind and Heart, while in the case of Aggregation, A uses B e.g. Organization uses People as an employee.

3) In UML diagram Association is denoted by a normal arrow head, while Composition is represented by filled diamond arrow head, and Aggregation is represented by an empty diamond arrow head, As shown in below and attached diagram in the third paragraph.

Association  A---->B
Composition  A-----<filled>B
Aggregation  A-----<>B

4) Aggregation is a lighter form of Composition, where a sub-part object can meaningfully exist without main objects.

5) In Java, you can use the final keyword to represent Composition. Since in Composition, Owner object expects a part object to be available and functions, by making it final, your provide a guarantee that, when Owner will be created, this part object will exist. This is actually a Java idiom to represent a strong form of association i.e. composition between two objects.

6) Another interesting word, which comes in handy to understand the 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 the 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.

That's all on the difference between Association, Composition, and Aggregation in UML, Java, and Object-oriented design. Since object-oriented analysis is more about defining the relationship between objects, it's important to know what kind of relationship exists between them, composition and aggregation is a two way of representing the relationship between two objects.


Few more articles to improve your object-oriented programming and design skills
Thanks for reading this article so far. If you find the difference between Association, Composition, and Aggregation clear and understandable then please share it with your friends and colleagues. If you have any questions, please drop a note. 


29 comments :

Unknown said...

Beautifully explained! Cheers!

Shiris said...

"cow HAS four legs " this is Composition but according to your example - "Car HAS driver" than it's Aggregation. so somewhere HAS working as composition and aggregation . confusion please clarify .

Unknown said...

Think it like this. If the container object dies, then the object inside container will die. If cow(container) dies, the objects(legs) are also dead. This is composition. That is not the case in aggregation. If car(container) dies, not necessary that the object(driver) should die. Hence this is aggregation. Hope this helps.

SARAL SAXENA said...

@Javin very perfectly explained..Thanks , lem me add the below points in short..


Association is a relationship where all objects have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation is a specialised form of Association where all objects have their own lifecycle but there is ownership and child objects can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not be destroyed. We can think about it as a “has-a” relationship.

Composition is again specialised form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have it's lifecycle and if parent object is deleted all child objects will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belong to two different houses. If we delete the house - room will automatically be deleted. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically be deleted.

javin paul said...

Hello Saral, nice to see you back here. Thanks for your useful comment and adding value to this article.

Anonymous said...

fantastic explanation. Thanks!

Anonymous said...

Could you please help me know the difference between the Association and Dependency?

Raju said...

can you explain why composition is preferred over inheritance

javin paul said...

Hello @Raju, welcome to Javarevisited. Please check my post on composition vs inheritance.

Larry Rix said...

Three possible relationships:

Is-a—inheritance
Has-a—reference
Expanded—in-line object

25 is an expanded type of INTEGER. When I write the code:

x = 25

The "25" is "expanded" by the compiler to an object directly in the enclosing object. Destroy the object and the expanded "25" INTEGER object goes away too.

A Has-a reference type is different. It is a field on a class which has a pointer to another object. Destroy the object with the reference and the object referenced remains (i.e. is not destroyed).

An Is-a inheritance relationship is the object itself. Destroying leaves a state that is self-evident (i.e. axiomatic).

Composition = Expanded
Aggregation / Association = Has-a

The difference between the two variants of Has-a reference type relationships is that when destruction of the enclosing object destroys the subordinate objects, then you have Aggregation. Otherwise, if the other objects are not destroyed, then the relationship is simple Association.

You control this. There is no magic. Actually, all objects live in either direct or indirect Aggregation of the root object and its creation procedure.

The notions of Aggregation, Association, and Composition are handy mnemonics to help you design. They are not "Object Oriented" themselves.

The only two true OO concepts are:

Reference Types
Expanded Types

Notions of Aggregation, Association, and Composition are loose design patterns to help you compose and design your object world.


Best Regards,
Larry

Manoj said...

Composition>>.
class Parent {
Child child;
Parent(){
child = new Child();
}
Aggregation>>
Class Parent{
Child child;
Parent (Child child){
this.child= child;
}
}

Correct me guys if i am wrong in concept
}

Blaze Kyo said...

you said that relationships between teachers and school should be association because when the school doesn't exist the teacher still can exist in another school.
What if the relationship between lecture of Taylor and Taylor? is it different now? Should it be a composition relationship now? because if Taylor University did not exist, lecturer of Taylor also wouldn't exist, lecturer in other universities is not lecturer of taylor university.

Satish Goda said...

Very nicely explained. Thank you!

Deepak Gakhar said...

Good one..

javin paul said...

Thank you @Satish and @Deepak, glad that you find information given here useful.

Arun Singh said...

composition represents 'has-a' relationship as i studied in java books, but here aggregation is 'has-a'. confused!!

Anonymous said...

@Arun, Composition, Aggregation, and Association all represent "has-a" relationship in some sort or other.

lu_morning said...

What's still confusing to me is why even have association at all? Since an association can be broken into aggregation and composition. I have yet to read an example that showed a difference between association and aggregation. Only reason you would include an association is if you don't know if objects are to be aggregation or composition or that it can be either one. But that would leave ambiguity.

Unknown said...

Hello, if Composition and Aggregation are both types of Associations, then why do we have a separate notation for Association in UML. A -> B. Could you give an example of an Association which is neither Aggregation nor Composition?
Thanks

Shaheed said...

Nicely explained

Unknown said...

driver is not part of the car.

Unknown said...

Nicely explained

ADWEB STUDIO said...

Composition = Expanded
Aggregation / Association = Has-a

The difference between the two variants of Has-a reference type relationships is that when destruction of the enclosing object destroys the subordinate objects, then you have Aggregation. Otherwise, if the other objects are not destroyed, then the relationship is simple Association. We are a a Web Design Company and it’d be a great opportunity for us to work with you :)

You control this. There is no magic. Actually, all objects live in either direct or indirect Aggregation of the root object and its creation procedure.

Unknown said...

Very clearly explained, well done and thank you,,,!

Anonymous said...

I wish people would stop explaining OOP using cars and body parts. Some proper examples related to software are much desired.

Deepak A L said...

In Aggregation, child object can belong to other parent object.

A single teacher can belong to multiple departments.

In case if the department is closed , the teacher can become a part of other department.

Example :: a Player which is part of a Team, can exist without a team and can become part of other teams as well.

Anonymous said...

Hi Javin, I could not understand that why you have marked the Engine class as final inside Car class in composition. What if we declare the Engine as non-final. And is your sample code the only way to demonstrate Composition in java-coding. Please respond and clarify. Thanks, Satya.

javin paul said...

Hello Satya, I think I have mentioned that it is to ensure that "there is no car without engine", when you make an instance variable final and don't initialize in constructor, compile will complain this way, its ensured that engine is always provided. If you have an optional dependency like a Car with a MusicSystem then you can mark it as non-final and then you get two option, constructor injection or setter injection, you can either initialize it on constructer or set it at runtime using setter methods. Does this clear your doubt? feel free to ask any other question you may have

Amatsai said...

Pls I need clarification on" " class composition "

Post a Comment