I have the following code
public static void main(String[] args) {
Engine engine = new Engine("This Engine!");
Car b = new Car(engine);
b = null;
}
Is this an aggregation? I always think that an aggregation is when something can still "live" even if the other class is "destroyed"... so for example Car and Engine. if I delete the Car instance, the Engine can still live.
Is this correct?
something can still "live" even if the other class is "destroyed".
Yes, Aggregation is where B exists independently from A, e.g an Employee still exists without his Manager.
Compostion is stronger where object A "owns" B. B has no purpose except in relation to A.
First, I would say that your code would look better when you do
would look better.
Then regarding your aggregation thinking, yes, you are correct. "Somehow". But this if you really split your "objects" fine grained. I mean, will you have a Car if it does not got an engine? :)
I would actually see the car as it is, I would think more an aggregation for a Car and a Driver. If Car is damaged still you have a Driver. And if a Driver dies, still you have a Car.
From
uml
about aggregation:Aggregation is a variant of the "has a" association relationship; aggregation is more specific than association. It is an association that represents a part-whole or part-of relationship. As a type of association, an aggregation can be named and have the same adornments that an association can. However, an aggregation may not involve more than two classes; it must be a binary association.
Aggregation can occur when a class is a collection or container of other classes, but the contained classes do not have a strong lifecycle dependency on the container. The contents of the container are not automatically destroyed when the container is.
Another relation which confuses with aggregation is the composition. When aggregation describes the "has" relation the composition do the "contains/part of" relation. As I said, normally, the engine is part of for you car object right (composition). The Car object has a Driver (aggregation).