IntelliJ IDEA 2017.2 Help

Replace Constructor with Factory Method

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

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"); } }

To replace a constructor with a factory method

  1. Select the class constructor.
  2. Open Replace Constructor With Factory Method dialog by choosing Refactor | Replace Constructor With Factory Method on the main menu or on tne context menu of the selection.
  3. In the Factory method name field, specify the name for the factory method.
  4. In the In (fully qualified name) field, specify the class, where the method should be created.
  5. To review the intended changes and make final corrections prior to the refactoring, click Preview. To apply the changes immediately, click Refactor.
Last modified: 29 November 2017

See Also