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, I follow the guidance of the great Josh Bloch, who considers that a positive use of static factory methods (Effective Java, Item 1).
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 know and teach that.