Encapsulate fields
The Encapsulate Fields refactoring lets you hide your data and create the necessary accessors.
Hiding your data and accessing it through an outward interface based on accessor methods is a good idea. Later you can change the data internals, preserving full compatibility with the code relied on the class and its available methods.
In the editor, place the caret at a class or at the desired field or at any place inside the class you want to refactor. (You can also use the Project tool window or Structure View for your selection.)
From the main menu or from the context menu, select .
In the dialog that opens, check the fields to which you want to create accessors, specify whether you want to create getter or setter methods. Plus, select the Use accessor even when field is accessible if you want to replace all field occurrences with the calls to the appropriate accessor method. You can also select visibility options.
Example
The following example shows how encapsulating a field changes the class that declares it and a class that references it.
Encapsulate Fields dialog
Use the Encapsulate Fields dialog to select which fields to encapsulate, which accessors to create for them, and which access modifiers to use.
Item | Description |
|---|---|
Fields to Encapsulate | Select the fields for which you want to create accessors. The Getter and Setter columns show suggested accessor names, which you can edit. |
Get access Set access | Select which accessors to create for the selected fields: getters, setters, or both. |
Use accessors even when field is accessible | Replace all references to the selected fields with accessor calls, even when the references can access the fields directly (for example, inside the same class). If you clear this option, references that can still access a field directly after the refactoring will keep this access. For example, if you set Encapsulated Fields' Visibility to Private, references inside the class will keep accessing the field directly, and only the references outside the class will change to accessor calls. |
Javadoc | This option appears only if at least one field has a Javadoc comment. Select what to do with Javadoc comments for the selected fields:
|
Encapsulated Fields' Visibility | Select the access modifier for the selected fields:
|
Accessors' Visibility | Select the access modifier for the new accessors:
|