title: Casting a generic superclass to a subclass
body: <p>This is my first SO question, I hope it's useful enough, both for readers and myself! I've googled and ducked the world around with this for the past two days.</p>
  
  <p>I have abstract model and storage classes from which concrete model and storage classes are derived:</p>
  
  <pre><code>abstract class Food {}
  
  abstract class FoodStorage&lt;T extends Food&gt; {
      abstract void setFood(T food);
  }
  
  class Apple extends Food {}
  
  class Basket extends FoodStorage&lt;Apple&gt; {
      @Override
      void setFood(Apple apple) {
          // Save that apple to the basket
      }
  }
  </code></pre>
  
  <p>No problem. Now, I would like to be able to call a <code>save()</code> directly on an <code>Apple</code> instance, persisting it to its <code>Basket</code> (without having to bother about the basket), and have that implemented in the abstract classes. The best I've found yet is this:</p>
  
  <pre><code>abstract class Food&lt;T extends Food&lt;T,S&gt;,
          S extends FoodStorage&lt;T,S&gt;&gt; {
  
      abstract S getStorage();
  
      void save() {
          getStorage().setFood((T)this); // &lt;---- Unchecked cast warning
      }
  
  }
  
  abstract class FoodStorage&lt;T extends Food&lt;T,S&gt;, S extends FoodStorage&lt;T,S&gt;&gt; {
      abstract void setFood(T food);
  }
  
  class Apple extends Food&lt;Apple,Basket&gt; {
      Basket basket = new Basket(); // or Basket.getInstance();
  
      @Override
      Basket getStorage() {
          return basket;
      }
  }
  
  class Basket extends FoodStorage&lt;Apple,Basket&gt; {
      @Override
      void setFood(Apple apple) {
          // Save that apple to the basket
      }
  }
  </code></pre>
  
  <p>Which works, but IntelliJ gives me a warning about the unchecked cast in <code>save()</code>. Indeed, I'm casting from <code>Food&lt;T,S&gt;</code> to <code>T</code>.</p>
  
  <p><strong>Question: how can I implement this <code>apple.save()</code> in a typesafe way?</strong></p>
  
  <p>I don't want any wildcards appearing in the client code, so changing <code>abstract void setFood(T food);</code> to <code>abstract &lt;Z extends Food&lt;T,S&gt;&gt; void setFood(Z food);</code> is not the solution. (Obviously I'm avoiding <code>SupressWarnings("unchecked")</code> also).</p>
  
  <p>I'm aware of <a href="https://stackoverflow.com/questions/5309922/java-generics-how-to-avoid-unchecked-assignment-warning-when-using-class-hierar">Java Generics, how to avoid unchecked assignment warning when using class hierarchy?</a> , of <a href="https://stackoverflow.com/questions/8093767/generics-cast-issue">Generics cast issue</a> , and of <a href="http://www.ibm.com/developerworks/java/library/j-jtp07018/index.html#3.0" rel="nofollow noreferrer">The get-put principle</a>, but I still can't get my head around it.</p>
  
  <p>Thanks in advance!</p>