This question follows from my Selenium question. In that question I am using a factory to create objects and I thought, perhaps mistakenly, that my class would not have a constructor if it is being instantiated by a factory. But, in the comments of the answer, MrTi recommends assigning something in the constructor.
Hence - can factory instantiated objects have constructors?
Yes they can and they should. But when using a factory you actually want to control the creation of the objects and thus somehow have to prevent other code from creating object by directly accessing the constructors, To do this you can have the factory in the same package as the class you want to create objects from and set the visibility of the constructors to package protected.
Yes. You just typically make the constructor only visible to the factory. In Java this is done by putting the factory in the same package as the classes it will be building and keeping the constructors package private (no access modifier).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With