I've just encountered an interesting problem related to Java generics. I'd like to use a concrete definition (DerivedPaginator) instead of "generified" definition (Paginator<Derived>). In order to do that, I have to change the method defined in the PaginatorTest. I've tried different combinations, but I still don't know how to do it.
Could you please help me with solving this puzzle?
interface Base {
}
interface Derived extends Base {
}
interface Paginator<T extends Base> {
}
interface DerivedPaginator extends Paginator<Derived> {
}
interface PaginatorTest<T extends Base> {
// how to define this method so that it would accept DerivedPaginator?
void check(Paginator<T> it);
// nice try, but no cigar
//<Y extends Paginator<T>> void check(Y it);
}
interface DerivedPaginatorTest extends PaginatorTest<Derived> {
// this works fine
//@Override
//void check(Paginator<Derived> it);
// but this doesn't
@Override
void check(DerivedPaginator it);
}
You may declare
interface PaginatorTest<T extends Base, Y extends Paginator<T>> {
void check(Y it);
}
and use it like
interface DerivedPaginatorTest extends PaginatorTest<Derived, DerivedPaginator> {
@Override
void check(DerivedPaginator it);
}
DerivedPaginator
extends Paginator<Derived>
, but a Paginator<Derived>
is not necessarily a DerivedPaginator
. I could make some other class that implements Paginator<Derived>
but not DerivedPaginator
, so you cannot guarantee that that argument to DerivedPaginatorTest .check()
is a DerivedPaginator
. I'm not even sure why you have the interface DerivedPaginator
which does not add anything to Paginator<Derived>
. Anyway, if you need to be able to have check()
method take something more specific than Paginator<T>
, you need to generify over that something too, like Howard shows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.