Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top