I have seen some ways to implement Composition. Composition is different from Aggregation by the fact that it is a type that lives and dies with the parent bean. Like in a Car Engine example, a car does not exist without Engine. An engine can not be taken out as reference and use it independently. It has complete dependency to the main class like Car here.
So, the ways can be using final for the type and instantiate the composed object in constructor(Engine in Car's constructor)
public class Car{
final Engine e;
Car(){
e = new Engine();
}
}
or the other way can be using an inner class, like, Engine class as inner class inside the Car class.
public class Car{
Engine e;
class Engine {
//valves, nuts and bolts
}
}
Please provide the best way? I went through several posts but none have the implementations of composition specific java code, only aggregation code is there:
Aggregation, Association and Composition
What is the difference between composition and aggregation?