IntelliJ IDEA 2018.2 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. Select the class constructor.
  2. On the main or context menu, select Refactor | 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

BeforeAfter
// 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 createClass(String s) { return new Class(s); } } // File AnotherClass.java public class AnotherClass { public void method() { Class aClass = Class.createClass("string"); } }
Last modified: 4 September 2018

See Also