简体   繁体   中英

Is there a way to have an interface with a generic type extend another interface with another generic type in Java?

I would like to create a interface like this

public interface MyInterface<T extends OtherInterface<K>>{
    K doSomething(T o);
}

but the compiler won't recognize it. The other way around is that:

public interface MyInterface<T extends OtherInterface<K>,K>{
    K doSomething(T o);
}

My question is, though the second code works, is there a way like the first code so I don't have to put two types to announce the interface?

If you have an generic interface with two type arguments, then you need to declare them both in the class signature.

Alternatively if declare K as a wildcard ? and just return T , you will still be able to cast the output T to the correct interface. eg:

interface Foo<T> { }

interface Bar<T extends Foo<?>>{
    T doSomething(T o);
}

class IntegerFoo implements Foo<Integer> {}
...

public static void main(String[] args) {
    IntegerFoo integerFoo = new IntegerFoo();

    Bar<IntegerFoo> bar = t -> t;

    Foo<Integer> result = bar.doSomething(integerFoo);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM