Search code examples
javaoopgenericsinheritanceabstraction

Java Bound Mismatch in recursive generics/inheritance


I have the following structure:

public abstract class A <E extends El, U extends A<E,U> > { ... }

public class B<E extends El> extends A<E, B<E> > { ... }

public abstract class C <E extends El, T extends A<E, T>> { ... }

My question is, why can I do this:

public class R extends C<El, B<El>> { ... }

but not

public class R <T extends B<El>> extends C<El, T> { ... }

Why is T (which extends B<El>) not a good substitute for B<El>?

The exception which I get is Bound mismatch: The type T is not a valid substitute for the bounded parameter <T extends A<El,T>> of the type C<E,T>


Solution

  • Try to declare A and C as follows

    public abstract class A <E extends El, U extends A<E, ? super U>> {}
    public abstract class C <E extends El, T extends A<E, ? super T>> {}