Note that there are some explanatory texts on larger screens.

plurals
  1. POChild-class cannot be cast to generic parent class
    text
    copied!<p>If have a type hierarchy that starts out with a generic type </p> <pre><code>class A&lt;T&gt; { ... } class B extends A&lt;Qux&gt; { ... } class C extends B { ...} </code></pre> <p>So far so good. Now I have a different class (also a generic) that uses A as parameter:</p> <pre><code>class Foo&lt;T&gt; extends Bar&lt;T&gt; { setA(A&lt;T&gt; a){ ...} } </code></pre> <p>Now I want to use all this:</p> <pre><code>Foo&lt;Qux&gt; foo = new Foo&lt;Qux&gt;(); foo.setA(new C()); </code></pre> <p>The last line gives an error "setA in type Foo is not application for the arguments C".</p> <p>I can't figure out what's wrong. In my opinion it should work because C extends B which extends A, which is the the parameter type that should be used ... thanks for any hints what is wrong with my assumptions.</p> <p><em>Update:</em> Using the code posted by Oli, I managed to get closer to the source of the error. It occurs once I replace B with my original class. So it must be located in the class that does away with the "generic" part. When trying to cast to the parent class Eclipse says it can't. I'll keep looking there, I know it should be working ... the problem can be reduced to this:</p> <pre><code>C c = new C(); A&lt;Qux&gt; a = (A&lt;Qux&gt;)c; </code></pre> <p>In my code this results in the error </p> <pre><code>Cannot cast from C to A&lt;Qux&gt; </code></pre> <p>I still have no idea why this happens. <strong>Is there any reason why a child class cannot be cast to it's parent class?</strong> There is no such reason. Because if you have such a problem it might just be your IDE. I restarted Eclipse for other reasons, checked again and it worked. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload