One benefit of having a class provide a static factory method rather than public constructors is the method can return an instance of a subclass.
For example, if the class Rectangle
had a subclass Square
, there could be a static method Rectangle.newInstance(int width, int length)
that sometimes returned a Rectangle
and sometimes a Square
.
What is a compelling example of the benefit of this approach? Students could easily ask in this case why the client didn't call the Square
constructor if the width and length are equal. (I can give them an answer to that question, but it would be better to have an example good enough that they wouldn't even ask.)
Edits
For those of you who answered that I shouldn't have a static factory method return an instance of a subclass, not only wasn't that my question but the great Josh Bloch considers that a positive use of static factory methods (Effective Java, Item 1). I recognize no higher Java authority, although you are free too.
For those who told me that a good use of static factory methods is that the programmer can choose their name, which is not the case with constructors, I already knew and teach that. (I'm not sure why you assumed I didn't.) If I wanted people's opinions on the best thing about static factory methods, I would have asked that, on Software Engineering Stack Exchange.
For those who answered the question I asked, thank you.