Search code examples
javaoopobjectclass-design

Do you create all object references in the main class or in the appropriate relationship class?


I have my main class PayUnit where I create my main object references, such as touchScreen, scale, and barcodeReader as these are has-a relationships to my PayUnit. This machine also has-a billDispenser but billDispenser is really 'is-a' relationship to currencyDispener. Do I still create a billDispenser and currencyDispenser object references in the main class, or do create a currencyDispenser reference in PayUnit and then create a billDispenser in the currencyDispenser class?

I hope that makes sense. What is the standard for OOP in this regard?

Thanks for the help.


Solution

  • From your description, it appears that there's no need to have the references to both billDispenser and currencyDispenser in PayUnit (since they are not separate entities, and one of them is an implementation of the other). A common practice is to define a protocol (an interface or an abstract class in Java) that describes the API of a module (in your case, currencyDispenser), and then have a factory method somewhere provide an implementation that conforms to that interface (billDispenser in your case). I hope this answers your question.