Sunday, November 18, 2012

UML Class Diagram Relationships, Aggregation, Composition

There are five key relationships between classes in a UML class diagram : dependency, aggregation, composition, inheritance and realization. These five relationships are depicted in the following diagram:

UML Class Relationships
The above relationships are read as follows:
  • Dependency : class A uses class B
  • Aggregation : class A has a class B
  • Composition : class A owns a class B
  • Inheritance : class B is a Class A  (or class A is extended by class B)
  • Realization : class B realizes Class A (or class A is realized by class B)
What I hope to show here is how these relationships would manifest themselves in Java so we can better understand what these relationships mean and how/when to use each one.

Dependency is represented when a reference to one class is passed in as a method parameter to another class. For example, an instance of class B is passed in to a method of class A:  
public class A {

    public void doSomething(B b) {

Now, if class A stored the reference to class B for later use we would have a different relationship called Aggregation. A more common and more obvious example of Aggregation would be via setter injection:
public class A {

    private B _b;

    public void setB(B b) { _b = b; }

Aggregation is the weaker form of object containment (one object contains other objects). The stronger form is called Composition. In Composition the containing object is responsible for the creation and life cycle of the contained object (either directly or indirectly). Following are a few examples of Composition. First, via member initialization:
public class A {

    private B _b = new B();

Second, via constructor initialization:

public class A {

    private B _b;

    public A() {
        _b = new B();
    } // default constructor

Third, via lazy init (example revised 02 Mar 2014 to completely hide reference to B):

public class A {

    private B _b;

    public void doSomethingUniqueToB() {
        if (null == _b) {
            _b = new B();
        }
        return _b.doSomething();
    } // doSomethingUniqueToB()

Inheritance is a fairly straightforward relationship to depict in Java:

public class A {

    ...

} // class A

public class B extends A {

    ....

} // class B


Realization is also straighforward in Java and deals with implementing an interface:

public interface A {

    ...

} // interface A

public class B implements A {

    ...

} // class B

Note: (added 3/2/14 in response to comments) Let me point out that in the above composition examples 'new' could be replaced with a factory pattern as long as the factory does not return the exact same instance to any two different containing/calling objects, which would violate the key tenet of composition which is that the aggregated objects do not participate in a shared aggregation (two different container objects sharing the same component part object). The builder pattern could also be used as long as the distinct 'parts' are not injected into more than one containing object.

6/29/2014 - here's a good article on class diagrams and answers Ivan's question below in the comments:

http://www.ibm.com/developerworks/rational/library/content/RationalEdge/sep04/bell/

57 comments:

Abhas said...

I am doing a project related to Commodity management using OOP concepts. I was really confused about class diagram before I visited your blog.. Very useful article.

Great job

-Abhas

Rim said...

I was having trouble distinguishing between the different forms of UML notations for object associations until I read this. Thanks for the concise explanation!

anna said...

Great work! You have explained the concepts with great clarity.

Anonymous said...

Great job! I found this post very useful so I created the corresponding UML model (using GenMyModel). It's public, feel free to clone it: http://app.genmymodel.com/genmymodel?clonedProject=966aeefb-50b8-45f6-b258-ca73fe2cc66a

Guru said...

The UML terms you described have very little distinction and always confusing. You explained them very well. Thanks for sharing.

Unknown said...

Thank you, very good tutorial, small and increadibly simple and easy. Good job!

Hini said...

Till now I was struggling to understand the concepts. Thanks a lot!!

Unknown said...

thank you so much. I found this very useful:)

Unknown said...

Thank you. This article was really helpful for my assignment.

Rick "NemuS" Rocha said...

Simple, clear, consistent

Thank you!

mastersheel007 said...

Best and easiest explanation......Thank you sir...

Unknown said...

It was very useful.
Thanks.

Unknown said...

Great work mate, simple and clear. I got a final exam in Object Oriented Programming in 2 hours and i was really confused with aggregation. thanks a lot, keep it up!

Unknown said...

Great explanation! It's very clear to understand!

ahmed said...

as said by almost it 's a cleat and concise explanation .thanks .

gw said...

Your explanataion of what is a composition in UML is not correct. The main characteristics of a composition is to have exclusive parts, and not the (optional) life-cycle dependency between an aggregate and its components.
See my StackOverflow answer.

Russ Jackson said...

Thanks gw. Your StackOverflow answer speaks for itself. To be more precise, the UML certification guide, for example, states that "the decisive characteristic of a composition is that the aggregated parts are never shared with other objects" (p. 49). Martin Fowler, in his book UML Distilled, 3rd ed. states similarly (p. 68) that "any instance must be a component of only one owner." Both of these are consistent with the UML spec reference Gangnus points out in his response on the StackOverflow question you cite.

Since my intent was to show how these relationships can be manifested in Java it was entirely appropriate to explain the lifecycle/ownership aspects of composition. As is stated in Applying UML and Patterns, 2nd ed. (p. 415), "In the Design Model, composition and its existence dependency implication indicates that composite software objects create (or caused the creation of) the part software objects".

The intent of my article was not to be complete, exhaustive, or verbose, but rather to try to succinctly explain how these relationships might be realized in a working system. I will revisit my word selection and see how I can best weave in the expert explanations referenced above.

Thanks.

Russ

Russ Jackson said...

Let me add that in Java, the only way I am aware of to guarantee the pure intent of composition (aggregated object not shared with other objects) is to control the lifecycle of it (directly via construction or indirectly via the containing object using a factory that returns a unique instance on every invokation) AND to control the visibility of it (i.e. make it private and never return/expose a direct reference to it).

Iván said...

Thanks a lot for your explanation, is the best i found for now.
Greetings from Spain!

Iván said...
This comment has been removed by the author.
Iván said...

Hello again. First of all, sorry for my english.
Well, im writing you because im starting with UML and i have a doubt that is killing me.
I know the difference between aggregation and composition, but i can´t understand the difference between aggregation and association with navigation (simple line with one arrow).
Are there any differences?

Unknown said...

Sreeni,
Good Work, very easy to understand.

Unknown said...
This comment has been removed by a blog administrator.
Unknown said...
This comment has been removed by a blog administrator.
Russ Jackson said...

Hi Lata,

Just a piece of advice - asking other people to do your work for you is not going to serve you well in the working world. If you would make an attempt at it and post your thoughts on it I'm sure we'd be happy to critique it for you. If you make an honest effort at it in the next week or so I'll consider leaving your comment on my blog. The second one was already removed as it was a duplicate.

Thanks.

Russ


If you or a loved one were sick and needed a doctor which one would you rather see - the one who studied, worked hard, earned their degree and knows what they're doing or the lazy one who relied on others to do their work for them and is incompetent? Which one do you want to be?

agung.imannuel said...

great explanation! its really helps other.

swadhin said...

excellent explanation, very easy and clear

Rudy said...

Thanks i needed really

Unknown said...

Nice article!

How would UML model a relationship where the life cycle is managed by the containing object but the contained/child object is exposed?

For example:

public class ShoppingList
{
public class Item
{
String name;
int quantity;
ShoppingList list;

public Item(ShoppingList list, String itemName)
{
...
}
}

private Item[] items;

public Item addItem(String name, int quantity)
{
...
}

public void removeItem(String name)
{
...
}

public Item[] getItems()
{
}
}

The idea is that an Item cannot exist without a shopping list and is never created independently of the shopping list. It is

Russ Jackson said...

Thanks Chris. This is interesting. You obviously have elements of both aggregation and composition.

Inside the item objects you have a reference to the ShoppingList. This would imply that an item could have only one owner (at a time).

However, that might depend on a couple things. If in getItems() you are returning the private items reference (rather than a copy of the list and its contents) then you have no control over the items. They could end up in an Order object that thinks it's the owner of the items. Even worse would be if an external entity modified the list and changed the internal state of your ShoppingList. The second thing would be to answer how would you implement hashCode() and equals(), if you had to, for the Item object?

Having said all that, we usually try to design before we code. Therefore, we would define the relationships up front and then implement that model with code. The question then becomes, how do you want the system to work?

Keep in mind, all aggregated objects are created by some other object. Just because an object creates another doesn't make it the owner in the sense of composition.

Evan said...
This comment has been removed by a blog administrator.
Unknown said...

Russ,

Thanks for reading a responding to my comment.

What I was hoping to learn was how to model a relationship that says that the child cannot exist without the relationship to the parent. From what I have been reading neither aggregation not composition imply this constraint. Do you agree? If so, how would you use UML to let a developer know that this constraint should exist?

Chris

Unknown said...

By the way, my understanding of UML class diagrams is that they model the static model of a system. Of course, we can have transient objects in any state but the system at rest must adhere to the constraints of the static model of the system.

Chris

Unknown said...

very very very very helpful!! Thnx a lot!!

Unknown said...
This comment has been removed by the author.
Evan said...
This comment has been removed by the author.
Evan said...

I got a question. Now Java is pure object oriented language, can be represented from UML of these concepts. But can Javascripts which has no co-relation to Java applied to object oriented concepts as well?

Regards,

Creately

Unknown said...

Thanks a lot man, I just understood the difference between agregation and composition.

Unknown said...

Thank you so much! I had looked through a lot of resources, however yours has been the only one with a simple explaination!
Thanks again!

Kamar 318 said...

thanks for good post, now i understand how to draw class diagram. So to do point with code example, ty !

suda said...

Hi Russ,

1. I have service class AssociateDetailsService. In this AssociateDetailsService class,I am creating the instance of DAO as below.

AssociateDAO assDAO = new AssociateDAO();
so, since i am creating new instance , is it a composition relation here?
Here I am not sure DAO is owned by service class.

2. I have single ton class ConnectionFactory. In the DAO, I am getting the single ton instance . so Can i use dependency or composition here?

In DAO getting singleton instance of
ConnectionFactory as below.

Connection con = ConnectionFactory.getInstance().getConnection();

Can you please clarify here

Thanks in advance

Barun Saha said...

Nice article!

Unknown said...

Well done great job!! I wish I had a teacher to explain me like this the UML Diagram

Harinder said...

simple n crisp detail..
nice article

chethan said...

Can you add the example for assocation and direct assoication !! . then this article becomes complete.

Unknown said...
This comment has been removed by a blog administrator.
Unknown said...
This comment has been removed by a blog administrator.
Praveen Rohira said...

Great article, very clear to understand.

Unknown said...

Dear Russ,

First off great article helped me a lot so far. Wondering if you could shed some light on this particular scenario:

Class A is passed an instance of Class B in it's constructor and saves it as a class member. I believe this is an Aggregation. Class A later calls a method of Class B which returns a new instance of Class C. Class B creates this new instance of Class C each time the method is called and does not store it at all just returns it. When Class A receives the instance of Class C from the method of Class B it too just returns it and doesn't store it as a class member.

So my questions:

1) The relationship between Class B and Class C, is this Composition because Class B created Class C or just Aggregation? Or is it in fact just a Dependency relationship as Class B doesn't store the instance of Class C it creates?

2) The relationship between Class A and Class C, is this a Dependency relationship?

Just by writing this question out I feel that the answer to both is that they are dependency relationships but it would be nice to have confirmation on that.

Thanks for taking the time to read this, I realise this blog entry is now almost 3 years old. Guess it's the price you pay for writing a quality post on the internet! =P

Kind Regards
Oliver

Russ Jackson said...

Nice job Oliver. You've got it. What you described would best be modeled by one of the behavioral diagrams, like a sequence diagram. But from a structural perspective (static perspective) they are both dependencies.

Thanks for the kind words.

Russ

andrews selvaraj said...

I Like this UML Diagrams...Very useful

Anonymous said...

thanks for these, very helpful

smith said...

Great article, I love these yes, but articles
It's good first approximation from the Java viewpoint, but:

I am "functional designer" in a project, so some kind of responsible for our UML model.
Comparing dependency and aggregation seems to be some kind of "implementation detail"?!
For me I would be "more save" or good enough using only depenedencies and never a "has a" relationships.
But actually I never use dependencies - and we generate Java classes from our model. (Perhaps I should even use more deps and drive the developers crazy :-))
To be seriously: from a functional viewpoint, UML seems to be a little over/ ill specified here?!

Chris said...

thanks, extremely helpful, i was struggling understanding class relationships till i read this post

Unknown said...

This is not correct regarding aggregation. You have omitted a common and important UML element -- association. An instance of class (A) holding on to a reference to an instance (or collection of instances) of another class (B) simply implies association (at a minimum). A farmer holding a reference to a cow would be an example. Livestock animals are not normally thought of as being a part of the person who owns them. Aggregation means that a B is part of an A, (e.g. a person is part of a club). I would suggest that anyone who is serious about this stuff spend some time reading the OMG standard for UML. It isn't always the most straightforward or helpful document but in struggling with it you will be have to do a bit of thinking and will (hopefully) come to a better understanding of each of the UML elements.

Unknown said...

Thanks...Really good article. Can you please provide examples in c++ for all these relationships ?

Dis said...

this article is very useful to understand concepts. it really helped me to clear my basic concepts.