Rajnish
Rajnish

Reputation: 54

LocalTime class is a final class but no constructor given, why?

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

Answers (1)

Gaurav Jeswani
Gaurav Jeswani

Reputation: 4592

There are multiple advantages of factory methods over constructor.

  1. Readable Names

  2. Polymorphism (Any instance of sub class can be returned)

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

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

Related Questions