Composition is a whole/parts relationship. A common way to code the composition relationship is to create the part object in the constructor of the composite (whole) object. Example in java:
public class Car {
private String brand;
private ArrayList<Tire> theFourTires = new ArrayList<Tire>();
public Car(String brand)
{
this.brand = brand;
for (int i = 1; i < 5;i ++)
{
// here the "composition" relationship
theFourTires.add(new Tire());
}
}
When we want to decide which objects will be the parts, we can use an add ... method to add the part object in the composite. You have to respect this rule (UML specifications) : the part object can not be shared (referenced by another object, except the composite). So, i think it's better, when you call the add method, not to have a reference on the part object in the method calling the add method, just like this, in the Car class:
public void addPart(CarParts aPart)
{
this.parts.add(aPart);
}
calling the add method from another object:
Car c = new Car("Ford Torino");
c.addPart(new Tire());
instead of
Tire t = new Tire();
c.addPart(t);
because in this case, the instance is shared, by t reference, even if it is for a very short time, and the composition relationship becomes an aggregation. In this case, you could call method on t object and violate encapsulation of the part object. The part objects have to be managed by the composite only. What do you think about this ? Thanks world !