Video in progress
What advantage do static factory methods like `List.of()` and `Integer.valueOf()` have over constructors?
A static factory method has a name, doesn't have to create a new object every time (it can return one from a cache), and can return an interface or a subclass. A constructor can do none of these.
📖 Answer
Three practical differences:
- A name.
Duration.ofSeconds(30)andDuration.ofMinutes(30)are immediately clear. Two constructors couldn't have the same(long)signature. - A cache.
Integer.valueOf(100)returns a ready object in the -128..127 range.new Integer(100)(deprecated) would create a new one every time. - The returned type.
List.of(1, 2)gives you aList, and behind it different hidden implementations are used depending on the number of elements. You don't even know their names.
var empty = Optional.empty(); // always the same object
var path = Path.of("/var/log"); // an implementation that fits the OS
var big = BigDecimal.valueOf(0.1); // avoids the trap of new BigDecimal(0.1)
The downside is that in the javadoc they don't stand out the way constructors do. That's why there are naming conventions: of, from, valueOf, getInstance, newInstance.
Sign up to mark studied questions and save your progress.