Example
| Before | After |
|---|---|
//File Class.java public class Class { public String aString; } |
//File Class.java public class Class { private String aString; public void setaString(String aString) { this.aString = aString; } public String getaString() { return aString; } } |
//File AnotherClass.java public class AnotherClass { public Class aClass; public void method() { aClass.aString="string"; } } |
//File AnotherClass.java public class AnotherClass { public Class aClass; public void method() { aClass.setaString("string"); } } |
- Select a class or a specific field within the class. The way you perform selection depends on the
view where you do it.
- In the editor: position the caret at the desired field or at any place inside the class to be refactored.
- In the Project view: select the desired class.
- In the Structure view: select one or more fields.
- On the main menu or on the context menu of the selection, choose . The Encapsulate Fields dialog box is opened, displaying all fields, detected in the selected scope.
- In the Fields to encapsulate area check the fields you want to create accessors for.
- In the Encapsulate area, specify whether you want to create getter or setter methods, or both.
- To replace all field occurrences with the calls to the appropriate accessor method, in the Options area check the option Use accessor even when field is accessible.
- In the Encapsulated fields' visibility area specify the new visibility scope for the selected fields.
- In the Accessors' visibility area select the visibility scope for the created accessor methods.
- Preview and apply changes.

