I have seen this at many places. a Parent class has a static method to create objects of the right subclass and at times we have a dedicated factory class with instance methods to create object of various subclasses.

Which one is used in which scenario ?

Like static factory methods of InetAddress in java.net to create subclasses of InetAddress Vs BorderFactory class to create various Borders.

  • Needing to modify the parent class when creating a new derived class is a poor code smell. Commented Mar 19, 2012 at 11:28

1 Answer 1


The second one; the separate class. That separate class should also have an interface. The reason is that this is the option that allows swapping the factory most easily, which is good for lowering coupling and for testability.

  • 1
    It might also be worth looking at Inversion of Control, or actually its close cousin Dependency Injection which some argue is a cleaner, more pluggable way to get the same behaviour. Commented Mar 19, 2012 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.