Builder: a static nested Builder separates construction from the product

The product's own constructor stays private, so the only way to create one is through its static nested Builder, which collects fields and calls build() at the end. This keeps the finished object's constructor from becoming an unreadable list of positional arguments.

Code
class Pizza {
    private final String size;
    private final boolean cheese;
    private Pizza(Builder b) { size = b.size; cheese = b.cheese; }
    public String toString() { return size + " pizza, cheese=" + cheese; }
    static class Builder {
        private String size = "medium";
        private boolean cheese = false;
        Builder size(String s) { size = s; return this; }
        Builder cheese(boolean c) { cheese = c; return this; }
        Pizza build() { return new Pizza(this); }
    }
}
Pizza pizza = new Pizza.Builder().size("large").cheese(true).build();
System.out.println(pizza);
Output
large pizza, cheese=true
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms