Here we have multiple custom query-DSLs that use related grammar. I am creating to create an AbstractBuilder
so that all the commonality can be written in one place. The problem is that is causes issues with method-chaining. When I try to chain from a method in to AbstractBuilder
so a subclass, it doesn't work without casting.
With these classes:
class AbstractBuilder{
protected final StringBuilder bldr = new StringBuilder();
AbstractBuilder addValue( String name, String value ){
bldr.append( name ).append( '=' ).append( value )append( ',' );
return this;
}
String toString(){
return bldr.toString();
}
}
class IntBuilder extends AbstractBuilder{
IntBuilder addValue( String name, int value ){
bldr.append( name ).append( '=' ).append( value )append( ',' );
return this;
}
}
This works
new IntBuilder().addValue( "age", 12 ).addValue( "name", "Bruce" ).toString();` but `new IntBuilder().addValue( "name", "Bruce" ).addValue( "age", 12 ).toString();
doesn't unless you make an ugly cast like:
((IntBuilder) (new IntBuilder().addValue( "name", "Bruce" ))).addValue( "age", 12 ).toString();
Now I guess I could override each methods and implement them with calls to their parents (via super.addValue( name, value );
), but that is really ugly.
How else can I get every method to return the current class and not the class on which it was defined?