2

I have a Class A with quite a number of member variables. In order to make it immutable and validate the member variables during construction, I made its constructor private and used an inner public static builder class (ClassABuilder) to build it. (Joshua Bloch Effective Java, Item 2).

Now what I do not understand is, how other programmers will subclass Class A to implemet their own specific behavior. I read through the disadvantages of Builder Pattern from the book but did not see subclassing mentioned as one. Am I missing something? Is there an elegant way around this?

Making the constructor protected was one of my thoughts, but it would still be taking the public static ClassABuilder, so how to add new member variables in the sub class?

Abe
  • 8,623
  • 10
  • 50
  • 74

2 Answers2

2

Create an inner public static ClassBBuilder builder in ClassB that is a subclass of ClassABuilder

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • That works. Is it some anti-pattern or something that is normally done? – Abe Dec 14 '11 at 12:45
  • 1
    This is object-oriented design. Then you can simply add to ClassBBuilder the additional member variables that were added to ClassB. – Jonathan Dec 14 '11 at 12:47
0

Why constructor of A use Buildler as a parameter. When user invokes Builder.create, builder must initialize default protected constructor of A, and then simply set of A's fields. So B you can easily inherit class B from A

korifey
  • 3,379
  • 17
  • 17
  • fields of class A are final so you cannot use setters. The builder needs to be passed in via constructor to set these final fields – Abe Dec 14 '11 at 12:53