Builder Pattern in Effective Java









up vote
127
down vote

favorite
37












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:



The class with multiple attributes and its builder class:



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;




Class where I try to use the above class:



public class Main 
public static void main(String args)
NutritionalFacts n =
new NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I am getting the following compiler error:




an enclosing instance that contains
effectivejava.BuilderPattern.NutritionalFacts.Builder
is required
NutritionalFacts n = new
NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I do not understand what the message means. Please explain. The above code is similar to the example suggested by Bloch in his book.










share|improve this question



















  • 1




    possible duplicate of An enclosing instance that contains <my reference> is required
    – Joshua Taylor
    Sep 26 '13 at 12:41














up vote
127
down vote

favorite
37












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:



The class with multiple attributes and its builder class:



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;




Class where I try to use the above class:



public class Main 
public static void main(String args)
NutritionalFacts n =
new NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I am getting the following compiler error:




an enclosing instance that contains
effectivejava.BuilderPattern.NutritionalFacts.Builder
is required
NutritionalFacts n = new
NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I do not understand what the message means. Please explain. The above code is similar to the example suggested by Bloch in his book.










share|improve this question



















  • 1




    possible duplicate of An enclosing instance that contains <my reference> is required
    – Joshua Taylor
    Sep 26 '13 at 12:41












up vote
127
down vote

favorite
37









up vote
127
down vote

favorite
37






37





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:



The class with multiple attributes and its builder class:



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;




Class where I try to use the above class:



public class Main 
public static void main(String args)
NutritionalFacts n =
new NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I am getting the following compiler error:




an enclosing instance that contains
effectivejava.BuilderPattern.NutritionalFacts.Builder
is required
NutritionalFacts n = new
NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I do not understand what the message means. Please explain. The above code is similar to the example suggested by Bloch in his book.










share|improve this question















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:



The class with multiple attributes and its builder class:



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;




Class where I try to use the above class:



public class Main 
public static void main(String args)
NutritionalFacts n =
new NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I am getting the following compiler error:




an enclosing instance that contains
effectivejava.BuilderPattern.NutritionalFacts.Builder
is required
NutritionalFacts n = new
NutritionalFacts.Builder(10).carbo(23).fat(1).build();




I do not understand what the message means. Please explain. The above code is similar to the example suggested by Bloch in his book.







java design-patterns builder-pattern






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 15 '13 at 15:33









Adam Liss

40.2k1193130




40.2k1193130










asked Feb 15 '11 at 17:48









Swaranga Sarma

6,721154777




6,721154777







  • 1




    possible duplicate of An enclosing instance that contains <my reference> is required
    – Joshua Taylor
    Sep 26 '13 at 12:41












  • 1




    possible duplicate of An enclosing instance that contains <my reference> is required
    – Joshua Taylor
    Sep 26 '13 at 12:41







1




1




possible duplicate of An enclosing instance that contains <my reference> is required
– Joshua Taylor
Sep 26 '13 at 12:41




possible duplicate of An enclosing instance that contains <my reference> is required
– Joshua Taylor
Sep 26 '13 at 12:41












9 Answers
9






active

oldest

votes

















up vote
155
down vote



accepted










Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.



public class NutritionFacts 
public static class Builder




Reference: Nested classes






share|improve this answer
















  • 28




    And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
    – Powerlord
    Feb 15 '11 at 18:01


















up vote
25
down vote













You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.



public class NutritionalFacts 
private final int sodium;
private final int fat;
private final int carbo;

public int getSodium()
return sodium;


public int getFat()
return fat;


public int getCarbo()
return carbo;


public static class Builder
private int sodium;
private int fat;
private int carbo;

public Builder sodium(int s)
this.sodium = s;
return this;


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;




And now you can set the properties as follows:



NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();





share|improve this answer






















  • Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
    – skia.heliou
    Mar 12 at 18:00

















up vote
13
down vote













To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder






share|improve this answer
















  • 2




    This has nothing to do with the question asked but very helpful! Nice find!
    – The Hungry Androider
    Aug 15 '14 at 19:13

















up vote
11
down vote













You are trying access a non-static class in a static way. Change Builder to static class Builder and it should work.



The example usage you give fails because there is no instance of Builder present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:



Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();


Because you would need to construct a new Builder every time.






share|improve this answer



























    up vote
    7
    down vote













    You need to declare the Builder inner class as static.



    Consult some documentation for both non-static inner classes and static inner classes.



    Basically the non-static inner classes instances cannot exist without attached outer class instance.






    share|improve this answer



























      up vote
      4
      down vote













      The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.






      share|improve this answer



























        up vote
        4
        down vote













        This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.



        NutritionalFacts n = new NutritionalFacts()

        Builder b = new n.Builder(10).carbo(23).fat(1).build();


        Nested Classes






        share|improve this answer


















        • 3




          that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
          – Bozho
          Feb 15 '11 at 18:11






        • 4




          true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
          – Damian Leszczyński - Vash
          Feb 15 '11 at 18:29

















        up vote
        0
        down vote













        I personally prefer to use the other approach, when you have 2 different classes. So you don't need any static class. This is basically to avoid write Class.Builder when you has to create a new instance.



        public class Person 
        private String attr1;
        private String attr2;
        private String attr3;

        // package access
        Person(PersonBuilder builder)
        this.attr1 = builder.getAttr1();
        // ...


        // ...
        // getters and setters


        public class PersonBuilder (
        private String attr1;
        private String attr2;
        private String attr3;

        // constructor with required attribute
        public PersonBuilder(String attr1)
        this.attr1 = attr1;


        public PersonBuilder setAttr2(String attr2)
        this.attr2 = attr2;
        return this;


        public PersonBuilder setAttr3(String attr3)
        this.attr3 = attr3;
        return this;


        public Person build()
        return new Person(this);

        // ....
        }


        So, you can use your builder like this:



        Person person = new PersonBuilder("attr1")
        .setAttr2("attr2")
        .build();





        share|improve this answer



























          up vote
          0
          down vote













          Once you've got an idea, in practice, you may find lombok's @Builder much more convenient.



          @Builder lets you automatically produce the code required to have your class be instantiable with code such as:



          Person.builder()
          .name("Adam Savage")
          .city("San Francisco")
          .job("Mythbusters")
          .job("Unchained Reaction")
          .build();


          Official documentation: https://www.projectlombok.org/features/Builder






          share|improve this answer




















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5007355%2fbuilder-pattern-in-effective-java%23new-answer', 'question_page');

            );

            Post as a guest






























            9 Answers
            9






            active

            oldest

            votes








            9 Answers
            9






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            155
            down vote



            accepted










            Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.



            public class NutritionFacts 
            public static class Builder




            Reference: Nested classes






            share|improve this answer
















            • 28




              And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
              – Powerlord
              Feb 15 '11 at 18:01















            up vote
            155
            down vote



            accepted










            Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.



            public class NutritionFacts 
            public static class Builder




            Reference: Nested classes






            share|improve this answer
















            • 28




              And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
              – Powerlord
              Feb 15 '11 at 18:01













            up vote
            155
            down vote



            accepted







            up vote
            155
            down vote



            accepted






            Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.



            public class NutritionFacts 
            public static class Builder




            Reference: Nested classes






            share|improve this answer












            Make the builder a static class. Then it will work. If it is non-static, it would require an instance of its owning class - and the point is not to have an instance of it, and even to forbid making instances without the builder.



            public class NutritionFacts 
            public static class Builder




            Reference: Nested classes







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 15 '11 at 17:54









            Bozho

            477k1069361055




            477k1069361055







            • 28




              And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
              – Powerlord
              Feb 15 '11 at 18:01













            • 28




              And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
              – Powerlord
              Feb 15 '11 at 18:01








            28




            28




            And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
            – Powerlord
            Feb 15 '11 at 18:01





            And, in fact, Builder is static in the example in the book (page 14, line 10 in the 2nd Edition).
            – Powerlord
            Feb 15 '11 at 18:01













            up vote
            25
            down vote













            You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.



            public class NutritionalFacts 
            private final int sodium;
            private final int fat;
            private final int carbo;

            public int getSodium()
            return sodium;


            public int getFat()
            return fat;


            public int getCarbo()
            return carbo;


            public static class Builder
            private int sodium;
            private int fat;
            private int carbo;

            public Builder sodium(int s)
            this.sodium = s;
            return this;


            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;




            And now you can set the properties as follows:



            NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
            fat(5).build();





            share|improve this answer






















            • Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
              – skia.heliou
              Mar 12 at 18:00














            up vote
            25
            down vote













            You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.



            public class NutritionalFacts 
            private final int sodium;
            private final int fat;
            private final int carbo;

            public int getSodium()
            return sodium;


            public int getFat()
            return fat;


            public int getCarbo()
            return carbo;


            public static class Builder
            private int sodium;
            private int fat;
            private int carbo;

            public Builder sodium(int s)
            this.sodium = s;
            return this;


            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;




            And now you can set the properties as follows:



            NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
            fat(5).build();





            share|improve this answer






















            • Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
              – skia.heliou
              Mar 12 at 18:00












            up vote
            25
            down vote










            up vote
            25
            down vote









            You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.



            public class NutritionalFacts 
            private final int sodium;
            private final int fat;
            private final int carbo;

            public int getSodium()
            return sodium;


            public int getFat()
            return fat;


            public int getCarbo()
            return carbo;


            public static class Builder
            private int sodium;
            private int fat;
            private int carbo;

            public Builder sodium(int s)
            this.sodium = s;
            return this;


            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;




            And now you can set the properties as follows:



            NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
            fat(5).build();





            share|improve this answer














            You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.



            public class NutritionalFacts 
            private final int sodium;
            private final int fat;
            private final int carbo;

            public int getSodium()
            return sodium;


            public int getFat()
            return fat;


            public int getCarbo()
            return carbo;


            public static class Builder
            private int sodium;
            private int fat;
            private int carbo;

            public Builder sodium(int s)
            this.sodium = s;
            return this;


            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;




            And now you can set the properties as follows:



            NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
            fat(5).build();






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 8 at 8:46









            Dónal

            120k155478748




            120k155478748










            answered Jul 31 '15 at 19:44









            Raj Hassani

            75211018




            75211018











            • Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
              – skia.heliou
              Mar 12 at 18:00
















            • Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
              – skia.heliou
              Mar 12 at 18:00















            Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
            – skia.heliou
            Mar 12 at 18:00




            Why not just make the NutritionalFacts fields public? They're already final, and it would still be immutable.
            – skia.heliou
            Mar 12 at 18:00










            up vote
            13
            down vote













            To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder






            share|improve this answer
















            • 2




              This has nothing to do with the question asked but very helpful! Nice find!
              – The Hungry Androider
              Aug 15 '14 at 19:13














            up vote
            13
            down vote













            To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder






            share|improve this answer
















            • 2




              This has nothing to do with the question asked but very helpful! Nice find!
              – The Hungry Androider
              Aug 15 '14 at 19:13












            up vote
            13
            down vote










            up vote
            13
            down vote









            To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder






            share|improve this answer












            To generate an inner builder in Intellij IDEA, check out this plugin: https://github.com/analytically/innerbuilder







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 31 '14 at 10:09









            analytically

            22344




            22344







            • 2




              This has nothing to do with the question asked but very helpful! Nice find!
              – The Hungry Androider
              Aug 15 '14 at 19:13












            • 2




              This has nothing to do with the question asked but very helpful! Nice find!
              – The Hungry Androider
              Aug 15 '14 at 19:13







            2




            2




            This has nothing to do with the question asked but very helpful! Nice find!
            – The Hungry Androider
            Aug 15 '14 at 19:13




            This has nothing to do with the question asked but very helpful! Nice find!
            – The Hungry Androider
            Aug 15 '14 at 19:13










            up vote
            11
            down vote













            You are trying access a non-static class in a static way. Change Builder to static class Builder and it should work.



            The example usage you give fails because there is no instance of Builder present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:



            Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();


            Because you would need to construct a new Builder every time.






            share|improve this answer
























              up vote
              11
              down vote













              You are trying access a non-static class in a static way. Change Builder to static class Builder and it should work.



              The example usage you give fails because there is no instance of Builder present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:



              Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();


              Because you would need to construct a new Builder every time.






              share|improve this answer






















                up vote
                11
                down vote










                up vote
                11
                down vote









                You are trying access a non-static class in a static way. Change Builder to static class Builder and it should work.



                The example usage you give fails because there is no instance of Builder present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:



                Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();


                Because you would need to construct a new Builder every time.






                share|improve this answer












                You are trying access a non-static class in a static way. Change Builder to static class Builder and it should work.



                The example usage you give fails because there is no instance of Builder present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:



                Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();


                Because you would need to construct a new Builder every time.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 15 '11 at 17:54









                Michael K

                1,81221935




                1,81221935




















                    up vote
                    7
                    down vote













                    You need to declare the Builder inner class as static.



                    Consult some documentation for both non-static inner classes and static inner classes.



                    Basically the non-static inner classes instances cannot exist without attached outer class instance.






                    share|improve this answer
























                      up vote
                      7
                      down vote













                      You need to declare the Builder inner class as static.



                      Consult some documentation for both non-static inner classes and static inner classes.



                      Basically the non-static inner classes instances cannot exist without attached outer class instance.






                      share|improve this answer






















                        up vote
                        7
                        down vote










                        up vote
                        7
                        down vote









                        You need to declare the Builder inner class as static.



                        Consult some documentation for both non-static inner classes and static inner classes.



                        Basically the non-static inner classes instances cannot exist without attached outer class instance.






                        share|improve this answer












                        You need to declare the Builder inner class as static.



                        Consult some documentation for both non-static inner classes and static inner classes.



                        Basically the non-static inner classes instances cannot exist without attached outer class instance.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Feb 15 '11 at 17:53









                        Grzegorz Oledzki

                        16.2k115286




                        16.2k115286




















                            up vote
                            4
                            down vote













                            The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.






                            share|improve this answer
























                              up vote
                              4
                              down vote













                              The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.






                              share|improve this answer






















                                up vote
                                4
                                down vote










                                up vote
                                4
                                down vote









                                The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.






                                share|improve this answer












                                The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Feb 15 '11 at 17:53









                                Shaun

                                2,3311432




                                2,3311432




















                                    up vote
                                    4
                                    down vote













                                    This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.



                                    NutritionalFacts n = new NutritionalFacts()

                                    Builder b = new n.Builder(10).carbo(23).fat(1).build();


                                    Nested Classes






                                    share|improve this answer


















                                    • 3




                                      that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
                                      – Bozho
                                      Feb 15 '11 at 18:11






                                    • 4




                                      true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
                                      – Damian Leszczyński - Vash
                                      Feb 15 '11 at 18:29














                                    up vote
                                    4
                                    down vote













                                    This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.



                                    NutritionalFacts n = new NutritionalFacts()

                                    Builder b = new n.Builder(10).carbo(23).fat(1).build();


                                    Nested Classes






                                    share|improve this answer


















                                    • 3




                                      that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
                                      – Bozho
                                      Feb 15 '11 at 18:11






                                    • 4




                                      true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
                                      – Damian Leszczyński - Vash
                                      Feb 15 '11 at 18:29












                                    up vote
                                    4
                                    down vote










                                    up vote
                                    4
                                    down vote









                                    This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.



                                    NutritionalFacts n = new NutritionalFacts()

                                    Builder b = new n.Builder(10).carbo(23).fat(1).build();


                                    Nested Classes






                                    share|improve this answer














                                    This mean that you cant create enclose type. This mean that first you have to cerate a instance of "parent" class and then from this instance you can create nested class instances.



                                    NutritionalFacts n = new NutritionalFacts()

                                    Builder b = new n.Builder(10).carbo(23).fat(1).build();


                                    Nested Classes







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Jun 9 '16 at 5:22









                                    MBH

                                    7,5651168116




                                    7,5651168116










                                    answered Feb 15 '11 at 17:53









                                    Damian Leszczyński - Vash

                                    24.9k74587




                                    24.9k74587







                                    • 3




                                      that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
                                      – Bozho
                                      Feb 15 '11 at 18:11






                                    • 4




                                      true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
                                      – Damian Leszczyński - Vash
                                      Feb 15 '11 at 18:29












                                    • 3




                                      that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
                                      – Bozho
                                      Feb 15 '11 at 18:11






                                    • 4




                                      true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
                                      – Damian Leszczyński - Vash
                                      Feb 15 '11 at 18:29







                                    3




                                    3




                                    that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
                                    – Bozho
                                    Feb 15 '11 at 18:11




                                    that doesn't make much sense, because he needs the builder to construct the "facts", not the other way around.
                                    – Bozho
                                    Feb 15 '11 at 18:11




                                    4




                                    4




                                    true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
                                    – Damian Leszczyński - Vash
                                    Feb 15 '11 at 18:29




                                    true if we focus on builder pattern, i focused only on "I do not understand what the message means", and presented one of two solutions.
                                    – Damian Leszczyński - Vash
                                    Feb 15 '11 at 18:29










                                    up vote
                                    0
                                    down vote













                                    I personally prefer to use the other approach, when you have 2 different classes. So you don't need any static class. This is basically to avoid write Class.Builder when you has to create a new instance.



                                    public class Person 
                                    private String attr1;
                                    private String attr2;
                                    private String attr3;

                                    // package access
                                    Person(PersonBuilder builder)
                                    this.attr1 = builder.getAttr1();
                                    // ...


                                    // ...
                                    // getters and setters


                                    public class PersonBuilder (
                                    private String attr1;
                                    private String attr2;
                                    private String attr3;

                                    // constructor with required attribute
                                    public PersonBuilder(String attr1)
                                    this.attr1 = attr1;


                                    public PersonBuilder setAttr2(String attr2)
                                    this.attr2 = attr2;
                                    return this;


                                    public PersonBuilder setAttr3(String attr3)
                                    this.attr3 = attr3;
                                    return this;


                                    public Person build()
                                    return new Person(this);

                                    // ....
                                    }


                                    So, you can use your builder like this:



                                    Person person = new PersonBuilder("attr1")
                                    .setAttr2("attr2")
                                    .build();





                                    share|improve this answer
























                                      up vote
                                      0
                                      down vote













                                      I personally prefer to use the other approach, when you have 2 different classes. So you don't need any static class. This is basically to avoid write Class.Builder when you has to create a new instance.



                                      public class Person 
                                      private String attr1;
                                      private String attr2;
                                      private String attr3;

                                      // package access
                                      Person(PersonBuilder builder)
                                      this.attr1 = builder.getAttr1();
                                      // ...


                                      // ...
                                      // getters and setters


                                      public class PersonBuilder (
                                      private String attr1;
                                      private String attr2;
                                      private String attr3;

                                      // constructor with required attribute
                                      public PersonBuilder(String attr1)
                                      this.attr1 = attr1;


                                      public PersonBuilder setAttr2(String attr2)
                                      this.attr2 = attr2;
                                      return this;


                                      public PersonBuilder setAttr3(String attr3)
                                      this.attr3 = attr3;
                                      return this;


                                      public Person build()
                                      return new Person(this);

                                      // ....
                                      }


                                      So, you can use your builder like this:



                                      Person person = new PersonBuilder("attr1")
                                      .setAttr2("attr2")
                                      .build();





                                      share|improve this answer






















                                        up vote
                                        0
                                        down vote










                                        up vote
                                        0
                                        down vote









                                        I personally prefer to use the other approach, when you have 2 different classes. So you don't need any static class. This is basically to avoid write Class.Builder when you has to create a new instance.



                                        public class Person 
                                        private String attr1;
                                        private String attr2;
                                        private String attr3;

                                        // package access
                                        Person(PersonBuilder builder)
                                        this.attr1 = builder.getAttr1();
                                        // ...


                                        // ...
                                        // getters and setters


                                        public class PersonBuilder (
                                        private String attr1;
                                        private String attr2;
                                        private String attr3;

                                        // constructor with required attribute
                                        public PersonBuilder(String attr1)
                                        this.attr1 = attr1;


                                        public PersonBuilder setAttr2(String attr2)
                                        this.attr2 = attr2;
                                        return this;


                                        public PersonBuilder setAttr3(String attr3)
                                        this.attr3 = attr3;
                                        return this;


                                        public Person build()
                                        return new Person(this);

                                        // ....
                                        }


                                        So, you can use your builder like this:



                                        Person person = new PersonBuilder("attr1")
                                        .setAttr2("attr2")
                                        .build();





                                        share|improve this answer












                                        I personally prefer to use the other approach, when you have 2 different classes. So you don't need any static class. This is basically to avoid write Class.Builder when you has to create a new instance.



                                        public class Person 
                                        private String attr1;
                                        private String attr2;
                                        private String attr3;

                                        // package access
                                        Person(PersonBuilder builder)
                                        this.attr1 = builder.getAttr1();
                                        // ...


                                        // ...
                                        // getters and setters


                                        public class PersonBuilder (
                                        private String attr1;
                                        private String attr2;
                                        private String attr3;

                                        // constructor with required attribute
                                        public PersonBuilder(String attr1)
                                        this.attr1 = attr1;


                                        public PersonBuilder setAttr2(String attr2)
                                        this.attr2 = attr2;
                                        return this;


                                        public PersonBuilder setAttr3(String attr3)
                                        this.attr3 = attr3;
                                        return this;


                                        public Person build()
                                        return new Person(this);

                                        // ....
                                        }


                                        So, you can use your builder like this:



                                        Person person = new PersonBuilder("attr1")
                                        .setAttr2("attr2")
                                        .build();






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered May 17 at 8:52









                                        winter

                                        907826




                                        907826




















                                            up vote
                                            0
                                            down vote













                                            Once you've got an idea, in practice, you may find lombok's @Builder much more convenient.



                                            @Builder lets you automatically produce the code required to have your class be instantiable with code such as:



                                            Person.builder()
                                            .name("Adam Savage")
                                            .city("San Francisco")
                                            .job("Mythbusters")
                                            .job("Unchained Reaction")
                                            .build();


                                            Official documentation: https://www.projectlombok.org/features/Builder






                                            share|improve this answer
























                                              up vote
                                              0
                                              down vote













                                              Once you've got an idea, in practice, you may find lombok's @Builder much more convenient.



                                              @Builder lets you automatically produce the code required to have your class be instantiable with code such as:



                                              Person.builder()
                                              .name("Adam Savage")
                                              .city("San Francisco")
                                              .job("Mythbusters")
                                              .job("Unchained Reaction")
                                              .build();


                                              Official documentation: https://www.projectlombok.org/features/Builder






                                              share|improve this answer






















                                                up vote
                                                0
                                                down vote










                                                up vote
                                                0
                                                down vote









                                                Once you've got an idea, in practice, you may find lombok's @Builder much more convenient.



                                                @Builder lets you automatically produce the code required to have your class be instantiable with code such as:



                                                Person.builder()
                                                .name("Adam Savage")
                                                .city("San Francisco")
                                                .job("Mythbusters")
                                                .job("Unchained Reaction")
                                                .build();


                                                Official documentation: https://www.projectlombok.org/features/Builder






                                                share|improve this answer












                                                Once you've got an idea, in practice, you may find lombok's @Builder much more convenient.



                                                @Builder lets you automatically produce the code required to have your class be instantiable with code such as:



                                                Person.builder()
                                                .name("Adam Savage")
                                                .city("San Francisco")
                                                .job("Mythbusters")
                                                .job("Unchained Reaction")
                                                .build();


                                                Official documentation: https://www.projectlombok.org/features/Builder







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 10 at 11:00









                                                torina

                                                1,06311525




                                                1,06311525



























                                                     

                                                    draft saved


                                                    draft discarded















































                                                     


                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function ()
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5007355%2fbuilder-pattern-in-effective-java%23new-answer', 'question_page');

                                                    );

                                                    Post as a guest














































































                                                    這個網誌中的熱門文章

                                                    What does pagestruct do in Eviews?

                                                    Dutch intervention in Lombok and Karangasem

                                                    Channel Islands