Reputation: 16116
I have an abstract class with a generic using a bounded type parameter to limit this type:
public abstract class AbstractCreator<T extends Request> {
....
}
Then I have multiple children from AbstractCreator and one uses another bounded type parameter, like next:
public abstract class AbstractBigCreator<U extends BigRequest> extends AbstractCreator<U> {
U request;
...
}
The interfaces bounded types are like next:
public interface Request<T extends Some> {
T getRequest();
}
public interface BigRequest<T extends SomeOther> extends Request<T> {
}
My problem is this child with another bounded type parameter is limiting to its the father class bounded type parameter in the class itself instead of this type parameter. So if I call the method getRequest()
from U request
I get that it is <T extends Some>
instead of <T extends SomeOther>
.
I expect:
U request;
request.getRequest(); //Class <T extends SomeOther>
But instead I get:
U request;
request.getRequest(); //Class <T extends Some>
Anyone knows what's happening?
Upvotes: 1
Views: 254
Reputation: 34470
The problem is not that the request
attribute is of type Request
instead of BigRequest
in your AbstractBigCreator
class.
The actual problem is that your BigRequest
interface is extending the Request
interface, so you are inheriting the definition of the T getRequest()
method. And in Request
, the T
type is bounded to Some
, and so is in BigRequest
.
The easiest solution is to redefine the T getRequest()
method in the BigRequest
interface, so that covariance is applied to the return type of the getRequest
method. This means that the getRequest
method of the BigRequest
interface would return SomeOther
instead of Some
.
Just do this:
public interface BigRequest<T extends SomeOther> extends Request<T> {
@Override
T getRequest();
}
And you'll be able to access SomeOther
after calling request.getRequest()
in AbstractBigCreator
.
Upvotes: 1