DEV Community

Sheng Wu
Sheng Wu

Posted on • Updated on

Effective Java - Static factory methods vs Constructors

Most of the time when we want to obtain an instance of a class, we call the public constructor. But we can also have a static factory method to simply return an instance of the class. For example:

public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE
Enter fullscreen mode Exit fullscreen mode

Advantages of using a static factory method

  • They have names. It is easier for clients to understand what the method is for. Also normally a class can only have one constructor given one signature. Changing the order of parameter list to get away from this restriction is bad practice. Because static factory methods have names, they don't share this restriction.
  • Unlike constructors, they are not required to create a new object every time they are invoked. For the example above, it uses the instance created in the class.
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
Enter fullscreen mode Exit fullscreen mode
  • Unlike constructors, they can return any subtype of the return type. For example, the interface java.util.Collections has many implementations and most of them are exported via static factory methods. The classes of returned objects are nonpublic, eg. EmptySet. It is exported via a static factory method
public static final Set EMPTY_SET = new EmptySet<>();
public static final <T> Set<T> emptySet() {
     return (Set<T>) EMPTY_SET;
Enter fullscreen mode Exit fullscreen mode

Disadvantages of using a static factory method

  • Classes without public / protected constructors cannot have subclasses.
  • These methods can be hard to find unlike constructors but there are some common names for static factory methods, e.g from(), and of().

When to use a static factory method

  • When you need multiple constructors with the same signature.
  • When objects are expensive to create.
  • When you want the flexibility to return subtypes.


In general, static factory methods are preferable than constructors. So think about them before using a constructor.

Top comments (0)