Replace constructor with builder
The Replace Constructor with Builder refactoring helps hide a constructor, replacing its usages with the references to a newly generated builder class, or to an existing builder class.
Place the caret at the constructor invocation to be replaced.
On the main or context menu, select
In the dialog that opens, if you need, change the suggested setter names. Specify whether you want to initialize the generated fields in the builder.
If you specify an initial value that matches the parameter value in the constructor invocation, you can skip setter method for such parameter by selecting the Optional Setter checkbox. You can also specify whether you want to create a new or use the existing builder.
Preview and apply the changes.
Example
public class apples {
public static void main(String[] args) {
variety varietyObject = new variety("Red Delicious");
varietyObject.saying();
}
}
// variety class
public class variety {
private String string;
// constructor
public variety(String name) {
string = name;
}
public void setName(String name) {
string = name;
}
public String getName() {
return string;
}
public void saying() {
System.out.printf("On sale today : %s\n", getName());
}
}
// variety builder is created
public class varietyBuilder {
private String name;
public varietyBuilder setName(String name) {
this.name = name;
return this;
}
public variety createVariety() {
return new variety(name);
}
}
// varietyBuilder added instead of constructor to the main class "apples.java"
public class apples {
public static void main(String[] args) {
variety varietyObject = new varietyBuilder().setName("Red Delicious").createVariety();
varietyObject.saying();
}
}
Last modified: 02 August 2022