"Frederik Vanderhaegen" wrote...
Can anyone explain me the difference between aggregation and composition?
I know that they both are "whole-part" relationships and that composition
parts are destroyed when the composition whole is destroyed.
Under a "whole-part" relationship I understand the following:
the whole can't exists without the parts, but can the parts exist without
the hole?
f.e.: a car can't exist without an engine
private engine _Engine
public car(engine oEngine){
this._Engine=oE ngine
}
but, is it possible to create an engine without that a car
has been created?
That's both the point and the question.
Both association and composition as OO concepts are just that, *concepts* to
be used at the "conceptual level" when you're designing your application.
The "car-engine" example as such isn't that good as an example, as you can
decide to go either way, or rather, it depends on what you want to allow.
It also seems that you're somewhat confused to what these concepts actually
means.
Composition: When you "destroy" the whole, the parts are also destroyed.
Aggregation: When you "destroy" the whole, the parts can still continue to
exist.
A pretty clear (and classic) example of "aggregatio n" is a course with
students. You can say that the course "aggregates " its students, but when
you delete the course from the system (e.g. it's finished), the students
themselves remain, e.g. as students in other courses.
It's harder to find the need for "true" composition, as you in almost any
case can find some possiblity to "reuse" the parts. But that's why they're
just "concepts". If you don't find a need to keep the engine when the car
crashed, that's your choice... ;-)
An example I sometimes use is a hotel with rooms. The hotel is composed of
rooms, as they won't exist without the hotel.
Implementation-wise...
They're only references anyway... ;-)
HTH
// Bjorn A