Course contentsShow
← Java
Lesson 620 of 2,87015. Nested and Inner ClassesFree lesson

Builder Pattern with Static Nested Classes

See how the Builder pattern commonly uses static nested classes for fluent object construction.

Builder Pattern with Static Nested Classes

What You'll Learn

You'll see how static nested classes enable the popular Builder pattern for creating complex objects with a clean, fluent API.

Why the Builder Pattern Uses Static Nested Classes

When constructing objects with many optional parameters, constructors can become unwieldy—either you have multiple overloaded constructors (the "telescoping constructor" problem) or you use setters that leave objects temporarily inconsistent. The Builder pattern solves this by using a separate builder object to gradually assemble the final product.

Static nested classes are perfect for builders because:

  • They're tightly coupled to the outer class they build
  • They logically belong together (the builder only exists to create instances of the outer class)
  • They can access private constructors of the outer class
  • The organization keeps your code clean and maintainable

The Pattern in Action

public class Person {
    private final String firstName;
    private final String lastName;
    private final int age;
    private final String address;

    // Private constructor - only Builder can call it
    private Person(Builder builder) {
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.age = builder.age;
        this.address = builder.address;
    }

    public static class Builder {
        private final String firstName; // required
        private final String lastName;  // required
        private int age;                // optional
        private String address;         // optional

        public Builder(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public Builder age(int age) {
            this.age = age;
            return this; // enables chaining
        }

        public Builder address(String address) {
            this.address = address;
            return this;
        }

        public Person build() {
            return new Person(this);
        }
    }
}

// Usage: fluent and readable
Person person = new Person.Builder("John", "Doe")
    .age(30)
    .address("123 Main St")
    .build();

Notice how the Builder accesses Person's private constructor and fields, while users get a clean, self-documenting API.

Key Takeaway: The Builder pattern leverages static nested classes to provide controlled, fluent object construction while maintaining encapsulation and keeping related code together.