title: Java self-typed methods: cannot safely cast to actual type
body: <p>Consider the following class, which I believe is correctly called a <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=136394" rel="nofollow">self-typed</a> class:</p>
  
  <pre><code>public abstract class Example&lt;E extends Example&lt;E&gt;&gt; {
    /** Constructs an instance of the subclass */
    protected abstract E construct();
  
    /** Do a private operation in the base class */
    private void specialOp() {}
  
    public E get1() {
      E obj = construct();
      // Error: The method specialOp() from the type Example&lt;E&gt; is not visible
      obj.specialOp();
      return obj;
    }
  
    public E get2() {
      Example&lt;E&gt; obj = construct();
      obj.specialOp();
      // Warning: Type safety: Unchecked cast from Example&lt;E&gt; to E
      return (E)obj;
    }
  
    public E get3() {
      E obj = construct();
      ((Example&lt;E&gt;)obj).specialOp();
      return obj;
    }
  }
  </code></pre>
  
  <p>That is to say, implementations extending this class would have a type signature like so:</p>
  
  <pre><code>public class SubExample extends Example&lt;SubExample&gt;
  </code></pre>
  
  <p>Each of the three <code>get*()</code> methods ostensibly do the same thing - construct a subclass of <code>Example</code>, execute a private method on the instance, and return it as its subtype.  However only the last example compiles without warnings.</p>
  
  <p>The behavior in <code>get1()</code> is an error even without generics, consider:</p>
  
  <pre><code>public class Example {
    private void specialOp() {};
  
    public void get(SubExample e) {
      // Error: The method specialOp() from the type Example is not visible
      e.specialOp();
    }
  
    public static class SubExample extends Example {}
  }
  </code></pre>
  
  <p>Which I understand, even if it seems unnecessarily restrictive to me.  And similarly <code>get3()</code> makes sense, though I dislike needing to cast like that.  But <code>get2()</code> confuses me.  I understand <code>E</code> is technically a subtype of <code>Example&lt;E&gt;</code>, but don't the bounds of this generic ensure that all <code>Example&lt;E&gt;</code>s are also <code>E</code>s?  If so, why is it not safe to cast like this?  Is it ever possible to cast from <code>Example&lt;E&gt;</code> to <code>E</code> without a warning?</p>