1. Technology




Composition is a relationship between two classes that is based on the aggregation relationship. Composition takes the relationship one step further by ensuring that the containing object is responsible for the lifetime of the object it holds. If Object B is contained within Object A, then Object A is responsible for the creation and destruction of Object B. Unlike aggregation, Object B cannot exist without Object A.


Imagine you create a Student class that holds information about individual students at a school. One piece of information stored is the student's date of birth. It's held in a GregorianCalendar object:

 import java.util.GregorianCalendar;
 public class Student {
   private String name;
   private GregorianCalendar dateOfBirth;
   public Student(String name, int day, int month, int year)
     this.name = name;
     this.dateOfBirth = new GregorianCalendar(year, month, day);
 //rest of Student class..

As the student class is responsible for the creation of the GregorianCalendar object it will also be responsible for its destruction (i.e., once the Student object no longer exists neither will the GregorianCalendar object). Therefore the relationship between the two classes is composition because Student has-a GregorianCalendar and it also controls its lifetime. The GreogrianCalender object cannot exist without the Student object.


# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Related Video
Create Bullet, Number, and Definition Lists in HTML
Creating Webpage Frames
  1. About.com
  2. Technology
  3. Java
  4. Java Glossary
  5. C
  6. Definition for the Term Composition

©2014 About.com. All rights reserved.