Alan Allen
Alan Allen

Reputation: 71

Coding composition in java

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 !

Upvotes: 0

Views: 1345

Answers (3)

Amongalen
Amongalen

Reputation: 3131

Wouldn't it be the best to create a defensive copy in the addPart() method? Something like that:

public void addPart(CarParts aPart)
{
    this.parts.add(new CarParts(aPart);
}

I assume you want those to be inaccessible by everyone.

Upvotes: 0

Pete Kirkham
Pete Kirkham

Reputation: 49311

A given association may or may not be navigable, and may or may not be a composition. If it is navigable, then something else can navigate it and get to the target of the association (the tyre) from the source (the car). Navigability does not affect whether the association is a composition. Encapsulation enforces navigability, not composition.

Upvotes: 0

AntoineB
AntoineB

Reputation: 4694

I don't think it matters at all, since, as long as you have a getter to access your 4 tires, you can get a reference to the Tire object which is not managed by Car anymore.

Since there is no delete operator in Java, the Car object has no possibility to delete the 4 Tire objects that it is linked to, and consequently there is no need for a composition type of relationship, and it isn't possible to materialize it either code wise.

Upvotes: 1

Related Questions