cxxr / better-java

Resources for writing modern Java
Other
5.79k stars 729 forks source link

Builder method and inheritance #19

Closed Superpat closed 9 years ago

Superpat commented 9 years ago

I've been testing out this method on a fairly standard school assignment, the only issue I'm encountering is how to handle inheritance.

Let's say I have an Employee class with an EmployeeBuilder, with a firstname, lastname, hiredate and salary, I then extend this class into a supervisor class and add a bonusrate member to it, should I extend the EmployeeBuilder or just create a new SupervisorBuilder from scratch?

The specific problem I've run into is the SupervisorBuilder methods return the Employee class instead of the Supervisor class.

zhouhaibing089 commented 9 years ago

I guess there would not be a clean solution, since as the Builder means, it builds a concrete class, nothing else, you just can not extends a builder and mix with it..

But anyway, here gives a approximately way to implement this(which also makes the code less readable)..

Superpat commented 9 years ago

Hmm.. while the solution presented in that thread works, its hardly an elegant solution, thanks anyway!

It's a shame too, I thought that covariant types would allow me to make this work without any hassle.

Superpat commented 9 years ago

Well it works, syntastic hates it and it looks like a hack, but it works.

Edit: On further notice, its not actually that bad, it looks a little weird for the superclass, but the inheriting classes seamlessly integrate it.