IntelliJ IDEA 2022.1 Help

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.

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

  2. On the main menu or on the context menu, select Refactor | Encapsulate Fields.

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

  4. Preview and apply changes.

Examples

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"); } }
Last modified: 10 August 2022