Skip to main content

Builder pattern in Java

Published 1 min readMarkdown
public class Employee {

    private final String firstName;
    private final String lastName;

    // private constructor, only Builder can call this
    private Employee(Builder builder) {
        this.firstName = builder.firstName;
        this.lastName  = builder.lastName;
    }

    // getters
    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    // static inner Builder class
    public static class Builder {
        private String firstName;
        private String lastName;

        public Builder firstName(String firstName) {
            this.firstName = firstName;
            return this;        // allows chaining
        }

        public Builder lastName(String lastName) {
            this.lastName = lastName;
            return this;        // allows chaining
        }

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

How to use it

Employee emp = new Employee.Builder()
        .firstName("John")
        .lastName("Doe")
        .build();
  • new Employee.Builder() creates a builder object.​

  • firstName("John").lastName("Doe") sets fields step by step.

  • build() finally creates the Employee.

No comments yet. Be the first to comment.