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.
Examples:
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..
}
No comments:
Post a Comment