How can I get subclasses to return their own type?
<p>Here we have multiple custom query-DSLs that use related grammar. I am creating to create an <code>AbstractBuilder</code> 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 <code>AbstractBuilder</code> so a subclass, it doesn't work without casting.</p>

<p>With these classes:</p>

<pre><code>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;
    }
}
</code></pre>

<p>This works <code>new IntBuilder().addValue( "age", 12 ).addValue( "name", "Bruce" ).toString();</code> but <code>new IntBuilder().addValue( "name", "Bruce" ).addValue( "age", 12 ).toString();</code> doesn't unless you make an ugly cast like: <code>((IntBuilder) (new IntBuilder().addValue( "name", "Bruce" ))).addValue( "age", 12 ).toString();</code></p>

<p>Now I guess I could override each methods and implement them with calls to their parents (via <code>super.addValue( name, value );</code>), but that is really ugly.</p>

<p>How else can I get every method to return the current class and not the class on which it was defined?</p>
