Encapsulating a Field
See Also
Field encapsulation is the act of restructuring your code so that a field
is accessed only by a pair of accessor methods. Accessor methods are
also referred to as read/write methods or getters and setters.
Typically when you encapsulate a field, you change the
field's access modifier to private so that the field can not
be directly referenced from outside of the class. For other classes to
reference the field, they have to use the accessor methods.
You can use the IDE's Encapsulate Fields command to:
- Generate accessor methods for fields. The names of these methods
take the form of getfield-name and setfield-name.
- Adjust the access modifier for the fields.
- Replace direct references in your code to the fields with
calls to the accessor methods.
To encapsulate a field:
- In the Source Editor, right-click a field or a reference to the field and choose
Refactor > Encapsulate Fields
from the contextual menu.
The Encapsulate Fields dialog box
opens.
- In the List of Fields to Encapsulate table, make sure the checkbox for
the field that you want to encapsulate is selected. You can select multiple fields.
- (Optional) Set the field's visibility.
- (Optional) Set the accessors' (getter and setter) visibility.
- (Optional) If you do not want the IDE to replace code to use the accessor
methods, clear the Use Accessors Even When Field is Accessible checkbox.
This option only has an impact if both of the following are true:
- You have direct references to the field in your
code.
- You have set the field's accessor modifier so that the field is visible
to the classes with these references.
- If you click Refactor, the IDE applies
the changes automatically and skips the remaining steps. If you click Preview,
the Refactoring window displays the lines of code that will be changed. Review
the list and clear the checkbox of any code that you do not want changed. If the
class that you are pushing members from has multiple subclasses and you do not
want the members to be pushed to all of them, be sure to clear the checkboxes
for the corresponding subclasses. Click Do Refactoring to apply the selected changes.
- You should always perform a clean build after completing
any refactoring commands. You can do a clean build by right-clicking the project's
node in the Projects window and choosing Clean and Build Project.
- See Also
- Refactoring: Quick Reference
- Moving a Class Member to a Superclass
- Moving a Class Member to a Subclass
- Changing a Method's Signature
- Extracting a Method
- Renaming a Field or Method
- Undoing Refactoring Changes
Legal Notices