Why do setter methods in the Builder design pattern return `this`?

Viewed 39

I want to know why setter methods has return this; in it. What does it mean?

new Person().setName("alex");
1 Answers

That's called a fluent interface.

The Builder pattern doesn't necessarily dictate that it has to be fluent, but that's often how it's implemented. It allows for users of the Builder to string together multiple calls (ie, "fluent"):

Persoon al = Person.builder()
            .setFirstName("Albert")
            .setLastName("Einstein")
            .setOccupation("Genius")
            .setGender(Gender.Male)
            .build();
Related