What's a good example of a static factory method returning instances of subclasses? 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.
I don't have a good answer to this. However here are my thoughts.
Named constructors
A good use for static factory, is to implement named constructors: Java, C#, C++, et al do not have named constructors. However named constructors can be useful, as they allow you to document different ways of constructing an object. Therefore use a static factory, to create the object. The static factory will use private un-named constructors.
Problems with the pattern
However other uses of static factory seem to be an anti-pattern.
You now have a super-class depend on the sub-class. The sub-class already depends on the super-class.
The static constructor can also easily break the single responsibility principle: the class is a thing and a factory for a thing.