Java 8 – Why Does java.time Use Methods for Creating Objects Instead of Constructors?

javajava8

In the new java.time package the core classes are using the factory method of instead of a public constructor. Even though I like the cosmetics of the of method I can't see a good reason to not use a constructor. The documentation I've found just explains that this is the case and doesn't really go in to why it's the case.

Quote from tutorial:

Most of the classes in the Date-Time API create objects that are
immutable, meaning that, after the object is created, it cannot be
modified. To alter the value of an immutable object, a new object must
be constructed as a modified copy of the original. This also means
that the Date-Time API is, by definition, thread-safe. This affects
the API in that most of the methods used to create date or time
objects are prefixed with of, from, or with, rather than constructors,
and there are no set methods.

Best Answer

Factory methods allow simplifying the constructors - the difference which instance in time is represented by the Object can be separated from the calculation of the instant.

There are lots of factory methods, some doing String parsing, some converting from some other date or time representation, but all that can happen before the Object has to be created (if creating a new Object is even necessary at all - could also be a cached one).

Another big advantage is that factory methods can have descriptive names: the methods for parsing String representations are named e.g. LocalTime.parse - that is not possible with constructors.

Related Topic