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.)
On the main menu or on 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.
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");
}
}
|