title: Dynamic return type of implementation declared in abstract method
body: <p>I am looking for a way to have, in an abstract method, the return type to be the one of the implementation calling the method.</p>
  
  <p>In other terms, I would like to write something like that:</p>
  
  <pre><code>public class GenericClass {
  
    public &lt;T extends GenericClass&gt; T returnMyself() {
      return (T)this; // Compiler warning, unsafe cast
    }
  }
  
  public class Implem1 extends GenericClass {}
  
  public class Implem2 extends GenericClass {}
  
  public class Main {
  
    public static void main(String[] args) {
      Implem1 implem1 = new Implem1();
      Implem1 again1 = implem1.returnMyself(); // Works fine, the type is inferred by the type of again1, I think
      Implem1 again2 = implem1.&lt;Implem1&gt;returnMyself(); // Works fine, the type is explicitly asked by &lt;Implem1&gt;
      Implem2 again3 = implem1.returnMyself(); // Works fine while it shouldn't. 
    }
  
  }
  </code></pre>
  
  <p>What I am looking for is a way to declare the method so that at compilation time, returnMyself() can only return the type of the implementation invoking it (in my example, implem1 is of type Implem1), and ensure the code invoking cannot mistake/mix the types.</p>
  
  <p>I searched quite a lot but couldn't find my answer anywhere (some topics seem similar but want a more general case, not explicitly the type of the implementaion invoking the method).</p>
  
  <p>Some answers were correct, but always implied to override the method in each Implementation class, which may be cumbersome and bug-prone on my side. I'm ideally looking for a method that i would have to write only once in the Abstract class.</p>
  
  <p>Any help/answer appreciated :D</p>