Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameter T is not within its bound; should extend MyBaseClass

I'm dealing with some legacy code, trying to refactor and extract common code. I've ended up with the following hierarchy.

public interface MyInterface<T extends MyBaseClass> {...}
public class MyBaseClass {...}
public class MyClass extends MyBaseClass implements MyOtherInterface<MyClass> {...}

public interface MyOtherInterface<T extends MyOtherInterface<T>> {
    void func(MyInterface<T> context);  // Complains that T should extend MyBaseClass
}

In words, I want to specify that the parameter T passed to MyOtherInterface should be a class that extends MyBaseClass and implements MyOtherInterface. Something like this:

public interface MyOtherInterface<T extends MyOtherInterface<T extends MyBaseClass>>

How can I do this? I am trying to change as little as possible. I am not sure the above is possible and I might have to actually flip the hierarchy.

like image 265
s5s Avatar asked Nov 07 '22 06:11

s5s


1 Answers

From Oracle's Java tutorial:

Multiple Bounds

The preceding example illustrates the use of a type parameter with a single bound, but a type parameter can have multiple bounds:

<T extends B1 & B2 & B3> A type variable with multiple bounds is a subtype of all the types listed in the bound. If one of the bounds is a class, it must be specified first. For example:

Class A { /* ... */ } interface B { /* ... */ } interface C { /* ...
*/ }

class D <T extends A & B & C> { /* ... */ } If bound A is not specified first, you get a compile-time error:

class D <T extends B & A & C> { /* ... */ }  // compile-time error

Source: https://docs.oracle.com/javase/tutorial/java/generics/bounded.html

like image 56
s5s Avatar answered Nov 14 '22 23:11

s5s