Important notice about this site

I graduated from the University of Texas at Austin in December 2020. This blog is archived and no updates will be made to it.

Using builders in Java

June 13, 2019

Instead of using a constructor, one way to set up an object in Java is by using a builder. Since Java does not have keyword arguments like Python does, having a large amount of positional arguments in constructors might be confusing and makes code difficult to understand. Furthermore, constructors only take in one combination of data. On the other hand, builders can be created to take in a wide variety of types of data.

The premise of a builder involves creating private classes within a class for which you wish to build an object. This nested private class acts as the builder class. Each builder method returns the current builder object, modifying the state by one parameter and passing it on for the next builder method to use. Once everything's finished being built, a final method will return the actual finished object instead of another builder object.

Below is an example:

class BodyFeatures {
    private String hairColor, eyeColor;
    private boolean leftHanded;

    public BodyFeatures(String hairColor, String eyeColor) {
        this.hairColor = hairColor;
        this.eyeColor = eyeColor;
    }

    public static Builder buildBodyFeatures() {
        return new Builder();
    }

    private class Builder {
        private String hairColor, eyeColor;

        private Builder() {}

        private Builder hairColor(String hairColor) {
            this.hairColor = hairColor;
            return this;
        }

        private Builder eyeColor(String eyeColor) {
            this.eyeColor = eyeColor;
            return this;
        }

        private BodyFeatures build() {
            return new BodyFeatures(hairColor, eyeColor);
        }
    }
}

Then, in code, it could be used this way:

BodyFeatures bf = BodyFeatures.buildBodyFeatures()
    .hairColor("black")
    .eyeColor("blue")
    .build();

This seems like a lot of work to implement, so I don't recommend using a builder unless the builder significantly reduces setup work. Using a builder is probably best if you're able to automatically generate this code programmatically.

Back to blog

Back to top