Question

When I have 2 classes and I want to use composition like that:

 class A {
    B beans
    }

How can I set default values to B? And can I initialize it in A's constructor?

Was it helpful?

Solution

Depends on the language I suppose.

The general rule of the thumb is that the constructor needs to create the object and make sure it is in a valid state. So if in your case a valid state depends on whether or not the B class is initialised you can call the constructor of B. This will make sure that your class A whenever it is used is in a valid state and ready to use.

To get back on your question, yes you can assign a default value to B depending on the language.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top