Multilevel Java generic inheritance using extends on generic parameters

generics, java

Solution

All you need is

public class Third<T extends SomeConcreteClass> extends Second<T>

You just need to respecify the bound. It doesn't propagate like you think it does.

(I'm not positive of the reason for this, but I have some guesses -- what if it was `Third<T> extends Second<Foo<T>>`? The appropriate bound on `T` isn't obvious, if there even is one. So instead, it just doesn't propagate automatically; you have to specify it.)

Problem

I have ``` public class First<T> {} public class Second<T extends SomeConcreteClass> extends First<T> {} public class Third<T> extends Second<T> {} //Compile-time error ``` I get the compile-time error ``` Type argument T is not with bounds of type-variable T. ``` When I contruct a `Third`, I want to be able to give the generic parameter as `SomeConcreteClass` (or derived class thereof), and for a run-time error to be thrown if I've offered up a type that is not part of `SomeConcreteClass`'s inheritance hierarchy. I would think that the specification in `Second`'s declaration would simply propagate downward, i.e. it should be implicit in the declaration (and any instantiations) of `Third`. What's with the error?

Original source