title: Builder Pattern in Effective Java
body: <p>I have recently started to read Effective Java by Joshua Bloch. I found the idea of the Builder pattern [Item 2 in the book] really interesting. I tried to implement it in my project but there were compilation errors. Following is in essence what I was trying to do:</p>
  
  <p>The class with multiple attributes and its builder class:</p>
  
  <pre><code>public class NutritionalFacts {
      private int sodium;
      private int fat;
      private int carbo;
  
      public class Builder {
          private int sodium;
          private int fat;
          private int carbo;
  
          public Builder(int s) {
              this.sodium = s;
          }
  
          public Builder fat(int f) {
              this.fat = f;
              return this;
          }
  
          public Builder carbo(int c) {
              this.carbo = c;
              return this;
          }
  
          public NutritionalFacts build() {
              return new NutritionalFacts(this);
          }
      }
  
      private NutritionalFacts(Builder b) {
          this.sodium = b.sodium;
          this.fat = b.fat;
          this.carbo = b.carbo;
      }
  }
  </code></pre>
  
  <p>Class where I try to use the above class:</p>
  
  <pre><code>public class Main {
      public static void main(String args[]) {
          NutritionalFacts n = 
              new NutritionalFacts.Builder(10).carbo(23).fat(1).build();
      }
  }
  </code></pre>
  
  <p>I am getting the following compiler error:</p>
  
  <blockquote>
    <p>an enclosing instance that contains
    effectivejava.BuilderPattern.NutritionalFacts.Builder
    is required
                    NutritionalFacts n = new
    NutritionalFacts.Builder(10).carbo(23).fat(1).build();</p>
  </blockquote>
  
  <p>I do not understand what the message means. Please explain. The above code is similar to the example suggested by Bloch in his book.</p>