Search code examples
javabuilder

Why can I chain setters with a class with builder class inside but cannot on a instance of a normal class?


I've got introduced to builder pattern while learning java and I can't understand how builder can chain the setter methods.

//this one compiles
new AlertDialog.Builder().setApplyButton("apply").setText("stop");


//this one doesn't compile
new NormalAlert().setApplyButton("apply").setText("stop");


Solution

  • Builder methods return this (the builder instance itself) so that more methods can be called on it. Generally, the method named build is defined to return the constructed object.

    Example:

    public class Person {
      private String name;
      private Integer age;
    
      public static class Builder {
        private String name;
        private Integer age;
            
        public Builder name(String name){
          this.name = name;
          return this;
        }
    
        public Builder age(Integer age){
          this.age = age;
          return this;
        }
    
        public Person build() {
            return new Person(this);
        }
      }
    
      private Person(Builder builder) {
        this.name = builder.name; 
        this.age = builder.age;     
      }
    }