intermediateBuilder Pattern

Why is a builder for a class commonly implemented as a static nested class rather than a separate top-level class?

Static, because building an object does not require an existing instance of the class being built to already exist — you are using the builder specifically to create that first instance. Nested, specifically so the builder can access the outer class's private members, including a private constructor: making the target class's real constructor private is what actually forces every caller to go through the builder, since no code outside the class could otherwise call new on it directly. A top-level builder class would have no special access to a private constructor in a different class, so nesting is what makes the you-can-only-construct-this-through-the-builder guarantee possible rather than just conventional.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to Why might a team choose a hand-written Prototype interface over Java's built-in Cloneable and Object.clone()?← Back to all Low-Level Design & Design Patterns questions