What is the concept of a static factory method as a language feature, and how does it differ from using a constructor directly?
Last updated
A static factory method is a static method (e.g.
of(),valueOf(),getInstance()) that returns an instance instead of the caller usingnewdirectly.Unlike constructors, it can have descriptive names, return a cached or shared instance, and return a subtype or interface that hides the implementation.
Trade-offs: a class with only private constructors cannot be subclassed, and factories are harder to discover than constructors.
- https://medium.com/@emrbrkg/static-factory-methods-an-alternative-to-object-creation-with-constructors-e8ea8a559eea
- https://www.baeldung.com/java-constructors-vs-static-factory-methods
- https://www.bernardosulzbach.com/object-oriented-development/static-factory-vs-constructors/
- https://www.geeksforgeeks.org/java/difference-between-constructor-and-static-factory-method-in-java/
- https://www.geeksforgeeks.org/category/programming-language/java/page/138/