IntelliJ IDEA 2024.1 Help

Replace constructor with factory method

The Replace Constructor With Factory Method refactoring lets you hide a constructor and replace it with a static method which returns a new instance of a class.

  1. Place the caret at the class constructor in the editor and press Alt+Enter.

  2. From the list of available context actions, select Replace constructor with factory method.

    Replace constructor with factory method
  3. In the dialog that opens, specify the name of the factory method and the class where the method should be created.

  4. Preview and apply the changes.

Example

Before

After

// File Class.java public class Class { public Class(String s) { ... } } // File AnotherClass.java public class AnotherClass { public void method() { Class aClass = new Class("string"); } }
// File Class.java public class Class { private Class(String s) { ... } public static Class createClass(String s) { return new Class(s); } } // File AnotherClass.java public class AnotherClass { public void method() { Class aClass = Class.createClass("string"); } }

Replace constructor with factory method dialog

This dialog appears when you invoke the Replace constructor with factory method refactoring.

Item

Description

Factory method name

Specify here the name for the factory method.

In (fully qualified name)

Specify here the class, where the method will be created.

Last modified: 11 February 2024