1

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?

Association vs. Aggregation vs. Composition in Java

Aggregation and Composition in Java Code

hi.nitish
  • 2,732
  • 2
  • 14
  • 21
  • 2
  • 2
    Whether you use an inner class or not has nothing to do with the fact it's composition. It's simply a choice of where it is most logical to put the source code. – Andy Turner Jul 05 '17 at 08:41
  • I usually stick to the former, unless there is a reason not to. It's easier to deal with the compiled class files and I think it makes a project easier to navigate and understand. Reasons to go for the latter may be that it's quicker to implement, the component is very small, or the code is provided as an example on a website (as it's more succinct). – khriskooper Jul 05 '17 at 08:45
  • @OliverCharlesworth changed to "better". Thanks for reading my question so meticulously. – hi.nitish Jul 05 '17 at 18:57
  • @hi.nitish :) But even so, please define "better" - what criteria are you evaluating this by? – Oliver Charlesworth Jul 05 '17 at 18:58
  • 1
    best = "best practice"? – Rabbit Guy Jul 05 '17 at 19:00
  • This is totally opinionated. I don't like inner classes, so my advice is to go for the first option. But another guy might perfectly say that there's no point in creating a class that won't be used independently in a new file. So there's no such better way. Use the one you most like... – fps Jul 05 '17 at 19:47

0 Answers0