title: Polymorphic method return type down-casting in java
body: <p>So I don't know if this is possible I've tried searching it but maybe my search terms are off. Basically I'm wondering, is there a way to create a generic function/method in a super class that returns the downcast object.</p>
  
  <pre><code>class A {
      public &lt;downcasted type (in this example B if called from a B instance)&gt; test() {
          return this;
      }
  }
  
  class B extends A { }
  
  B b = new B().test()
  </code></pre>
  
  <p>basically having "test()" return the B instance as type B even know the function/method is declared purely in the parent class?</p>
  
  <p>I know I can cast the variable, tho having many functions some of which may return Lists of the class type, etc become troublesome. I also realize I could @override the function in B and do a "return (B)this.super()" thing, but again wrapping many functions is tedious and makes makes updating the base classes code more painful.</p>
  
  <p>I also know you can do </p>
  
  <pre><code>"class A&lt;T extends A&gt;"
  </code></pre>
  
  <p>and then define B as </p>
  
  <pre><code>"class B extends A&lt;B&gt;"
  </code></pre>
  
  <p>but then if you want to make a "C" that extends "B" it breaks.</p>
  
  <p>So is this type of behavior possible? If so, what is it called and how do I implement it?</p>
  
  <p>An example as to where this behavior could be useful would be any base data structures you want to make extendable like an N-Ary Tree that you extend into oct/quad tree structure and/or an extended class that adds a "Name" and "Attributes" or something for a xml-like node.</p>
  
  <p>Edit:
  This seems to work(as far as the linter is concerned), it's a bit more work to implement the base methods but it's got the desired end result as far as I can tell. That said when I attempt to run it, it gives me a "cannot find symbol: class type" error. :S</p>
  
  <pre><code>static class D extends auto {
  
      final Class type = getClass();
  
      @SuppressWarnings("unchecked")
      public &lt;T extends type&gt; T test() {
          return (T)type.cast(this);
      }
  }
  
  static class E extends D { }
  static class F extends E { }
  
  static {
      D d = new D().test();
      E e = new E().test();
      F f = new F().test();
  }
  </code></pre>