javadesign-patternsconstructoreffective-javastatic-factory

Effective Java Item1 - Static factory method for object creation


I was going through Effective java item 1, where "Static factory method vs constructors" for object creation is discussed. One of the disadvantages mentioned is the following:

"The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed."

It is also mentioned that this is good since it will promote object composition to inheritance. However, is it not a serious limitation, when you indeed want inheritance? Why should I prefer static factory methods for object creation, when I do not know from before if the class is going to be extended or not?


Solution

  • Why should I prefer static factory methods for object creation, when I do not know from before if the class is going to be extended or not?

    The answer to this question is in Effective Java Item 17: Design and Document for Inheritance or else Prohibit It. Designing a class for inheritance requires significantly more work, including the following.

    1. Documenting precisely the effects of overriding any method.
    2. Providing hook methods.
    3. Testing subclasses (by implementing those classes yourself).
    4. Restricting constructors to avoid all overridable methods.
    5. Considering the Cloneable and Serializable interfaces, and their effects on inheritance.

    If you have done all of this work, then you will not provide only static factory methods. You will also provide at least one public or protected constructor.

    Effective Java goes into detail on each of these points, but the final advice is,

    The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed.