Builder pattern in Java - Stack Overflowmost recent 30 from stackoverflow.com2026-04-14T06:12:59Zhttps://stackoverflow.com/feeds/question/25130510https://creativecommons.org/licenses/by-sa/4.0/rdfhttps://stackoverflow.com/q/251305101Builder pattern in Javauser2399453https://stackoverflow.com/users/23994532014-08-05T02:58:36Z2014-08-05T03:14:08Z
<p>IF I have a class that uses a builder pattern for construction because most params are optional how are default values specified? For instance in the situation below, if the client builds with only the compulsory item but later queries the optional items, what happens?</p>
<pre><code> public class BClass {
private final int compulsoryItem;
private final int optional1;
private final String optional2;
public int getCompulsoryItem() { return compulsoryItem; }
public int getOptional1() { return optional1; }
public int getOptional2() { return optional2; }
private BClass(Builder builder) {
this.compulsoryItem = builder.compulsoryitem;
this.optional1 = builder.optional1;
this.optional2 = builder.optional2;
}
public static class Builder {
private int compulsoryItem;
private int optional1;
private String optional2;
public Builder(int c) { this.compulsoryItem = c; }
public Builder opt1(int o1) { this.optional1 = o1; return this; }
public Builder opt2(String o2) { this.optional2 = o2; return this; }
public BClass build() { return new BClass(this); }
}
}
</code></pre>
https://stackoverflow.com/questions/25130510/-/25130619#251306191Answer by Bradley Kaiser for Builder pattern in JavaBradley Kaiserhttps://stackoverflow.com/users/11976702014-08-05T03:14:08Z2014-08-05T03:14:08Z<p>Just specify defaults in the Builder class. They aren't final in the builder, so they can be reassigned. You can't set the defaults in the actual BClass becasue all the fields are final.</p>