4 ms·
What’s the difference between 3 overloaded constructors and 3 overloaded factories + a constructor ? The factories will call the constructor, they kind of look
by zaphirplane 4y ago
What’s the difference between 3 overloaded constructors and 3 overloaded factories + a constructor ?
The factories will call the constructor, they kind of look similar
- kleiba 4y agoThe idea is that for cases where the initialization of the arguments to super() or this() become more complex, you provide a factory method (often only a single one) where these more complex computations take place and their results are then passed via "new" to one of the constructors, with the resulting object being the return value of the factory method. This makes it easy to create an object where such more complex values are needed for initialization, and it releases your code from jumping through hoops to circumvent the overly restrictive super/init-must-come-first policy, with constructions such as a number of private static methods that are never called from anywhere else besides the constructor. The constructors could still be public, so if you don't have the need to do anything fancy, you might still just call one of the simple constructors directly. However, you often see that API designers restrict this approach in favor to a single point of entry into creating objects of that class. That is, you then have to create objects via a factory, even if you could as easily pass already existing values to a simple constructor. But that's a different story.