Reputation: 54
Can we have a constructor of a final class. I know that String class have constructor, but I am looking specifically at LocalTime
class of java.time
package. It does not show any constructor. But one can get object of this class through static method like LocalTime.now()
. Why we don't have a constructor as simple as new(). Please throw light on this.
Upvotes: 1
Views: 252
Reputation: 4592
There are multiple advantages of factory methods over constructor.
Readable Names
Polymorphism (Any instance of sub class can be returned)
Coupling (Factory methods promote the idea of coding using Interface then implementation which results in more flexible code, but constructor ties your code to a particular implementation)
Caching (returning cached object rather than creating always new one)
Although all these advantages are not valid in this context, but creating multiple constructors make it unclear for the users to understand, which constructor has what details. Case where multiple constructor are possible replacing it with static factory methods make the object construction for the user more readable. And user can use correct initialization method by looking at the name.
Even Effective Java - from Joshua Bloch mentions about it very well. Considering all these advantages, it's valid to replace constructor with static initializer.
Upvotes: 4