title: Generic method return type - compilation error
body: <p>Given this code sample:</p>
  
  <pre><code>class A {
  
  }
  
  public class TestGenerics {
  
      private static &lt;T extends A&gt; T failsToCompile() {
          return new A();
      }
  
      private static &lt;T extends A&gt; T compiles(T param) {
          return param;
      }
  
  }
  </code></pre>
  
  <p>how come the first method doesn't compile, but the second one does?</p>
  
  <p>The error is:</p>
  
  <blockquote>
    <p>Incompatible types. Required: T. Found: A</p>
  </blockquote>
  
  <p>Essentially what I'm trying to achieve is to return a concrete instance of a sub-type (for example of class B, that extends A). Sort of a factory method.</p>
  
  <p><strong>Edit</strong>: OK, for those who downvoted, I decided to elaborate a bit further. See the updated example, which no longer uses String (yes I'm aware that String is final, no need to state the obvious)</p>
  
  <p><strong>Edit 2</strong>: alternative version of the question:</p>
  
  <p>How would you implement this method so that it compiles (without unchecked casts and warnings)?</p>
  
  <pre><code>abstract &lt;T extends A&gt; T failsToCompile();
  </code></pre>
  
  <p><strong>Edit 3</strong>: Here's a code sample closer to the problem I'm trying to solve:</p>
  
  <pre><code>class Foo { }
  class Bar extends Foo { }
  class A&lt;T extends Foo&gt; { }
  class B extends A&lt;Bar&gt; { }
  public class TestGenerics {
  
      private static &lt;T extends Foo&gt; A&lt;T&gt; failsToCompile() {
          return new B();
      }
  
  }
  </code></pre>
  
  <p>Here, the method return type is <code>A&lt;T&gt;</code>. Considering that <code>T</code> is defined as a <em>Foo or its subclass</em>, and the definition of B is as follows: <code>B extends A&lt;Bar&gt;</code>, why can't I just return <code>new B()</code>? I guess the problem comes down to the fact that you can't assign <code>List&lt;Animal&gt; dList = new ArrayList&lt;Dog&gt;();</code> and I understand why. But is there an elegant solution to this?</p>