This is not enough.
In relation to composition, if the whole instance is destroyed, the part instance must also be destroyed immediately .
To do this, you need to have some codes (some mechanisms).
For example, if you push Chapter instances from an external class (for example, using a constructor), you must be careful to remove these instances when the Book instance is deleted.
If your instances are created in the Book class (in a new way ...), there is no need to do anything, and Chapter instances will be deleted by the Book instance.
In this link: Object Prime, third edition (Scott W. Ambler, 2004)
in the section ( 13.4.12.7 Implementation of the composition )
As you might have guessed, aggregating and compositional associations are treated exactly like associations. The main difference, from a programming point of view, aggregation implies a tougher relationship between the two classes than association, and composition implies an even sharper relationship . Although FIG. 13.11 does not include compositional associations, the connection between the Workshop and the Course is tough, in fact, at least as tight as you would look with the composition (unfortunately, the sentence rule does not make sense in this case). In figure 13.31 you see the result of this closeness in the implementation of the remove () method in the class course - when deleting the course His workshops are also being deleted . This type of lifecycle management code is typical of hierarchies .
public void remove() { if (getSeminars() != null) {
Consider this example:
class Person { private final Brain brain; Person(Brain humanBrain) { brain = humanBrain; } }
And in other parts of the code, we can define it like this:
Brain b = new Brain(); // or we have an instance of Brain in other scopes // not exactly in this scope Person p1 = new Person(b); Person p2 = new Person(b);
So, in this code we can install one instance of Brain for two different Persons .
Note As part of this, we must manage the life cycle of instances . Just defining the private final any class, do not show the composition between them.
For example, the example below may be a composition. Since part instances are deleted when whole removed:
public class House { private final Room room; public House() { room = new Room(); } }
In composition:
whole may be directly responsible for the creation or destruction of the part . Or he can use the βpartβ that is already created and managed from outside the class (other parts of the code). In this case, the removal of part should be controlled by external code, and part should be deleted immediately after the removal of whole .
We must establish a mechanism to remove part when removing whole . If we do not remove part and use it in other wholes , this is Aggregation or Association .