I'm really having a hard understanding Composition and Aggregation. In the code below, I would like to know which of the following car instance uses composition logic or aggregation logic.
public class Engine {
public Engine() {
}
}
public class Car1 {
public final Engine engine;
public Car1() {
engine = new Engine();
}
}
class Car2{
public Engine engine;
public Car2(Engine engine) {
this.engine = engine;
}
}
class Car3{
public final Engine engine;
public Car3(Engine engine) {
this.engine = engine;
}
}
class Car4{
Engine engine;
public Car4(){
this.engine = new Engine();
}
}
class Main{
public static void main(String[] args) {
Engine engine = new Engine();
Car1 car1 = new Car1();
Car2 car2_1 = new Car2(new Engine());
Car2 car2_2 = new Car2(engine);
Car3 car3_1 = new Car3(new Engine());
Car3 car3_2 = new Car3(engine);
Car4 car4_1 = new Car4();
}
}
According to me, car1, car2_1, car3_1 follows Compostion logic. But I have read many places that car3_2 is also composition. Why? If we destroy car3_2 still engine instance would exist, so that should be Aggregation.