Jul 042011
 

The UML diagram shown below describes a composition relationship between Book and Page. This is a strong type of relationship — Book is responsible for creating, managing, and destroying all instances of Page.

The filled-in diamond indicates this is a composition relationship, and the arrowhead denotes the relationship is navigable in one direction only. A Book knows about every Page, but a Page does not know about its Book.

The multiplicity indicator (0..* ) next to Page means zero or more. We can therefore say that one Book has zero or more Page. We might assume that a book with zero pages is one that is on an author’s desk and about to be written.

The following code shows how I have implemented Book and Page classes in a simple Java program.

// Book.java

import java.util.List;
import java.util.ArrayList;

public class Book {
    private List pages = new ArrayList();

    public Book() {}
    public void addPage(String text) {
	Page page = new Page();
	page.addText(text);
	pages.add(page);
    }
    public String toString() {
	StringBuffer sb = new StringBuffer();
	for(Page page : pages) {
	    sb.append(page + "\n");
	}
	return sb.toString();
    }
    public int getPageCount() {
	return pages.size();
    }
    private boolean pageExists(int pageNum) {
	if(pages.size() == 0 || pageNum < 0 || pageNum >= pages.size()) {
	    return false;
	} else {
	    return true;
	}
    }
    public String getPage(int pageNum) {
	if(! pageExists(pageNum)) {
	    return null;
	}
	return pages.get(pageNum).toString();
    }
}

Page defines a very simple class. More operations (methods) could be added if required.

// Page.java

public class Page {
    private String text;

    public Page() {}
    public void addText(String text) {
	this.text = text;
    }
    public String toString() {
	return text;
    }
}

Notice how Book is responsible for managing each Page. There is no direct access to a Page object outside of the Book class.

// Demo.java

public class Demo {
    public static void main(String[] args) {
	Book book = new Book();

	book.addPage("Once upon a time,");
	book.addPage("something happened.");
	book.addPage("The end!");

	// display entire book
	System.out.println(book);

	// display single page
	System.out.println(book.getPage(2));

	// display page count
	System.out.println("Page count = "
			   + book.getPageCount());
    }
}

Thanks for reading this article. You’re welcome to ask questions and make suggestions by posting a comment below.

  4 Responses to “UML Composition Relationship — Java code example”

  1. This is just about the best example of Composition association that I have come across and, believe me, I have searched!

    I have two questions, but I think that I know the answer to the first. Still, here they are:

    1. Why does this code not use the composition association, when reverse-coded into UML, using Visual Paradigm? I suspect that it is because the composition (black filled diamond) is not coded in VP.
    2. More important to me though, is why the association doesn’t do more to define the relationship between Book and Page. As in, shouldn’t the association be able to qualify each Page, say with a Chapter number? And, once qualified, shouldn’t the association use the Create/Destroy methods held by Book, in order to create and manage the component pages?

    Thanks, again.

    • Hello Anthony,

      Thanks for your comments. I created the UML diagram using Dia Diagram Editor on Ubunutu. Although I’ve not tried Visual Paradigm, it’s interesting to hear about it and I see that there is a free Community Edition for non-commercial use.

      http://www.visual-paradigm.com/download/vpuml.jsp?edition=ce

      As for your suggestions about chapter numbers etc., these may be valid ideas but I wanted to use a simple example that everyone could understand. Feel free to post an updated example and/or link to more advanced solutions.

  2. Hi. I’m aggre with Anthony….Nice Example, the best I’ve found thanks :) Now I understan a little more about it :).. But I also have some questions.

    1. What if we also have a class called Book_cover, wich is relationed with book in the same Way that Page is related with book… except by the cardinality, a cover belongs only to one book, and a book has only one cover…

    In this case… would book have an atribute in the class diagramm of class cover? or it would not appear and we should supose it by the relation?

    2. In the same situation where we include the class Book_Cover… How we would implement the atribute Cover in book…
    it would be something like

    public class Book {
    private List pages = new ArrayList();
    private Book_Cover cover = new Book_cover();

    Or the “new Book_cover()” would be in the constructor of book?

    Thanks. and sorry for bad English, That’s not my natural language :P

  3. hi
    thank u very much for your example , there is plenty of developers that have no idea about how to implement The object oriented relationships (I mean Composition , Aggregation, Association) because we have lack of good examples I have some questions:

    1- what is your idea about an inner class , in your opinion , what is the relationship between an outer class and the inner class ? is that Composition or another one?
    2-could you please give an example about aggregation ?
    thank you very much , excuse me for my poor english ;)

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>