If the class of the object returned can be private (non-public), there is a degree of encapsulation where the private class can be modified without impacting clients of the API (possibly for bug-fixing or improvements, or just plain maintainence). The private classes can also vary depending on the parameters to the static factory, so long as they are subtypes of the return type, allowing for greater flexibility.
I really don't get the connection between class of returned object being private and degree of encapsulation. And how does that allow for greater flexibility? can anybody please explain more? or some examples?
Suppose that you have a public interface a public class that implements the interface, and a factory that creates instances of the interface.
And there's some code that uses the factory to create a new SomeThing object.
Note that the return type of the createThing() method of Factory is SomeThing, while it really returns a ConcreteThing. This means that code that uses the factory could cast the returned object into a ConcreteThing:
If for some reason the implementation of createThing() is changed so that it no longer returns a ConcreteThing (but it does still return a SomeThing), then code that casts the result to a ConcreteThing will break (a ClassCastException will be thrown at runtime).
So, even though the method signature of Factory.createThing() doesn't change, client code can still break because it might rely on how the method is implemented.
Suppose that we wrote the above code differently: instead of having a public class ConcreteThing, we return a private nested class.
Because class PrivateThing is private, no code outside of the Factory class can use it. So, client code cannot cast the object returned by createThing() into a PrivateThing.
This gives class Factory more freedom: the implementation of the createThing() method can be changed without breaking client code.