title: Java: returning subclass in superclass method signature
body: <p>I'm working on a problem where there are several implementations of <code>Foo</code>, accompanied by several <code>FooBuilder</code>'s. While <code>Foo</code>'s share several common variables that need to be set, they also have distinct variables that require their respective <code>FooBuilder</code> to implement some specific functionality. For succinctness, I'd like to have the <code>FooBuilder</code>'s setters to use method chaining, like: </p>
  
  <pre><code>public abstract class FooBuilder {
    ...
  
    public FooBuilder setA(int A) {
      this.A = A;
      return this;
    }
  
    ...
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>public class FooImplBuilder extends FooBuilder{
    ...
    public FooImplBuilder setB(int B) {
      this.B = B;
      return this;
    }
    public FooImplBuilder setC(int C) {
      this.C = C;
      return this;
    }
    ...
  }
  </code></pre>
  
  <p>And so on, with several different <code>FooBuilder</code> implementations. This technically does everything I want, however, this approach is sensitive to the order of methods calls when method chaining is performed. The following has method undefined compile errors:</p>
  
  <pre><code>someFoo.setA(a).setB(b)...
  </code></pre>
  
  <p>Requiring that the developer think about the order of method calls in the chain. To avoid this, I'd like to have the setters in <code>FooBuilder</code> somehow return the actual implementing subclass. However, I'm not sure how to do this. What is the best approach?  </p>