Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can factory created objects have constructors?

Tags:

java

oop

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?

like image 583
Friedrich 'Fred' Clausen Avatar asked Mar 20 '26 20:03

Friedrich 'Fred' Clausen


2 Answers

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.

like image 99
A4L Avatar answered Mar 22 '26 09:03

A4L


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).

like image 40
dcow Avatar answered Mar 22 '26 10:03

dcow