Builder pattern in Java - Stack Overflow most recent 30 from stackoverflow.com 2026-04-14T06:12:59Z https://stackoverflow.com/feeds/question/25130510 https://creativecommons.org/licenses/by-sa/4.0/rdf https://stackoverflow.com/q/25130510 1 Builder pattern in Java user2399453 https://stackoverflow.com/users/2399453 2014-08-05T02:58:36Z 2014-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#25130619 1 Answer by Bradley Kaiser for Builder pattern in Java Bradley Kaiser https://stackoverflow.com/users/1197670 2014-08-05T03:14:08Z 2014-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>