"Attempting to use an incompatible return type" 具有接口继承

"Attempting to use an incompatible return type" with Interface Inheritance

我 运行 遇到了使用继承的不兼容 return 类型的问题。

public interface A { }
public interface B extends A { }

public interface C {
    Map<String, A> getMapping();
}

public interface D extends C {
    Map<String, B> getMapping();
}

有没有办法让它工作?

现在编译器告诉我我在接口 D 上 'Attempting to use an incompatible return type'。

我建议你使用

interface C {
    Map<String, ? extends A> getMapping();
}

这表示 "A map that maps String to A or a subtype of A"。这与 Map<String, B>.

兼容

进行以下更改:

interface C<E extends A> {
    Map<String, E> getMapping();
}

interface D extends C<B> {
    Map<String, B> getMapping();
}

作为已接受答案的补充,我 运行 在使用嵌套类型数据结构时遇到了问题。例如,如果您在接口中创建一个抽象方法,例如:

Collection<Collection<? extends InterfaceB>> doSomething();

然后接受的答案将暗示这应该有效:

@Override
Collection<Collection<InterfaceBImplementation>> doSomething() {

... doing stuff...

return stuff;
}

但是,您将收到相同的 clashing/incompatible return 类型错误。相反,您还必须在抽象方法中通配内部集合:

Collection<? Collection<? extends InterfaceB>> doSomething();

我不明白为什么会这样,或者为什么要这样设置,但是你明白了。