IntelliJ IDEA 2022.2 Help

Convert to Instance Method

Convert to Instance Method refactoring lets you convert a static method to a non-static, class instance method, with a class being the type parameter of the initial method.

  1. In the editor, place the caret at the declaration or usage of a method that you want to refactor. The method should be static and the types of its parameters should be the classes from the project. Also note that you cannot use such parameters types as String.

  2. From the main menu, select Refactor | Convert to Instance Method.

    You can also use a context menu to access this refactoring.

  3. In the dialog that opens, select the class you want the method to belong to after the conversion. All the usages of this class inside the method are replaced with this.

    If you need, change the visibility scope of the converted method.

  4. Preview and apply changes.

Example

Consider classes MyClass, ClassB and ClassB residing in the same package.

As a result, MyClass and ClassB become converted.

Before

After

public class MyClass { ClassA classA = new ClassA(); ClassB classB = new ClassB(); static public void greatMethod(ClassA classA, ClassB classB){ System.out.println("classA = " + classA); System.out.println("classB = " + classB); } public void myMethod(){ MyClass.greatMethod(classA, classB); } }
public class MyClass { ClassA classA = new ClassA(); ClassB classB = new ClassB(); public void myMethod(){ classB.greatMethod(classA); } } public class ClassB { public void greatMethod(ClassA classA) { System.out.println("classA = " + classA); System.out.println("classB = " + this); } }
Last modified: 29 November 2022