Convert to Instance Method
Refactor | Convert to Instance Method
This refactoring is also available from UML Class diagram.
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.
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 asString
.Go to Refactor | Convert to Instance Method.
You can also use a context menu to access this refactoring.
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.
Preview and apply changes.
Consider classes MyClass
, ClassB
and ClassB
residing in the same package.
As a result, MyClass
and ClassB
become converted.
Before
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); }}
After
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); }}
This dialog appears when you invoke the Convert to instance method refactoring.
Item | Description |
---|---|
Select an instance parameter | 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 |
Visibility | In this area you can change the visibility scope of the converted method. By default, the converted method will have no scope declaration (equivalent to |
Thanks for your feedback!