If have a type hierarchy that starts out with a generic type
class A<T> { ... }
class B extends A<Qux> { ... }
class C extends B { ...}
So far so good. Now I have a different class (also a generic) that uses A as parameter:
class Foo<T> extends Bar<T> {
setA(A<T> a){ ...}
}
Now I want to use all this:
Foo<Qux> foo = new Foo<Qux>();
foo.setA(new C());
The last line gives an error “setA in type Foo is not application for the arguments C”.
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.
Update: 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:
C c = new C();
A<Qux> a = (A<Qux>)c;
In my code this results in the error
Cannot cast from C to A<Qux>
I still have no idea why this happens. Is there any reason why a child class cannot be cast to it’s parent class? 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.
The following compiles fine for me:
Your problem must lie elsewhere.