IntelliJ IDEA 2016.2 Help

Make Method Static

The Make Method Static refactoring converts an instance method to a static one and automatically corrects all calls, implementations and overridings of the method.

Examples

BeforeAfter
class ConnectionPool { public int i; public int j; public void getConnection() { ... } }
class ConnectionPool { public int i; public int j; public static void getConnection(ConnectionPool connectionPool) { ... } }
class ConnectionPool { public int i; public int j; public void getConnection() { ... } }
class ConnectionPool { public int i; public int j; public static void getConnection(int i, int j) { ... } }

Performing the Refactoring

  1. Select the method to be refactored in the Structure view, or right-click the method name in the editor. On the main menu, or on the context menu of the selection, choose Refactor | Make Static. The Make Method Static dialog box opens.
  2. If the method references any of the containing class fields, do one of the following:
    • To pass the whole referenced object as a parameter to the method, select the Add object as a parameter with name check box and enter the name for the parameter.
    • To pass the referenced fields/variables as parameters to the method, select the Add parameters for fields check box and select the appropriate fields in the list. You can also change the order of the parameters using the Move Up and Move Down buttons.
  3. If the method does not contain any references to fields or instance variables, you should only specify whether you want to replace instance qualifiers with class references.
  4. To preview the results, click Preview and examine the reuslt of the refactoring in the Find tool window. Apply the changes, if no issues arizs.

Make Static refactoring for a method in a call hierarchy

In call hierarchies, if the method callers don't contain any other references to instance members, IntelliJ IDEA suggests that you make those callers static too.

Example

BeforeAfter
class CallHierarchySample { private void foo(int i) { bar(i);} private void bar(int i) { baz(i);} private void baz(int i) { } }
class CallHierarchySample { private static void foo(int i) { bar(i);} private static void bar(int i) { baz(i);} private static void baz(int i) { } }

In this example, the refactoring was performed on baz(int i). All the caller methods were selected for making static too.

When performing the refactoring, the Select Methods to Propagate Static dialog is shown. This dialog lets you select the caller methods to be made static.

SelectMethodsToPropagateStatic

See Also

Last modified: 23 November 2016