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:

To encapsulate a field:

  1. 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.

  2. 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.
  3. (Optional) Set the field's visibility.
  4. (Optional) Set the accessors' (getter and setter) visibility.
  5. (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:

  6. 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.
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