Is this an aggregation?

我怕爱的太早我们不能终老 提交于 2019-12-01 11:24:27

问题


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?


回答1:


First, I would say that your code would look better when you do

Car b = new Car();
b.setEngine(engine);

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.

composition/aggregation

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).




回答2:


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.



来源:https://stackoverflow.com/questions/29220051/is-this-an-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!