ConcreteA is not abstract and does not override abstract method doSomething(InterfaceA) in InterfaceC

huangapple go评论79阅读模式
英文:

ConcreteA is not abstract and does not override abstract method doSomething(InterfaceA) in InterfaceC

问题

我有以下的代码:

接口 InterfaceA {}

接口 InterfaceB extends InterfaceA {

}

接口 InterfaceC {
    public void doSomething(InterfaceA t);
}

类 ConcreteA implements InterfaceC {
    public void doSomething(InterfaceB t)    {
        // 做些什么
    }
}

但是我得到了以下的错误:

ConcreteA 不是抽象的,并且没有覆盖 InterfaceC 中的抽象方法 insert(InterfaceA)

现在,我的理解是因为 InterfaceB 从 InterfaceA 继承,所以我应该能够在需要 InterfaceA 的函数中使用 InterfaceB,但事实并非如此。有谁能解释一下为什么这行不通,并指点我解决问题的正确方向吗?

提前谢谢!

英文:

I have the following code:

interface InterfaceA {}

interface InterfaceB extends InterfaceA {

}

interface InterfaceC {
    public void doSomething(InterfaceA t);
}

class ConcreteA implements InterfaceC {
    public void doSomething(InterfaceB t)    {
        // Do something
    }
}

But I am getting the following error:

ConcreteA is not abstract and does not override abstract method insert(InterfaceA) in InterfaceC

Now, my understanding is because InterfaceB extends from InterfaceA, I should be able to use InterfaceB in a function which requires InterfaceA, but this is not the case. Can anyone explain to me why this doesn't work and point me in the right direction to solve it?

Thanks in advance!

答案1

得分: 3

以下是翻译好的内容:

但是,ConcreteA的方法签名与接口声明不同。
Java编译器期望在doSomething方法中传递的是准确的InterfaceA。

您需要将其更改为有效的方法之一:

class ConcreteA implements InterfaceC {
    public void doSomething(InterfaceA t) {
        // 做一些事情
    }
}

上述声明不会阻止您将实现了InterfaceB的对象作为参数传递,但方法声明必须与InterfaceC的定义匹配。

或者使用泛型类型进行支持:

interface InterfaceC<T extends InterfaceA> {
    void doSomething(T t);
}

class ConcreteA implements InterfaceC<InterfaceB> {
    public void doSomething(InterfaceB t) {
        // 做一些事情
    }
}
英文:

But method signature of ConcreteA is different than the interface declaration.
Java compiler expects exactly InterfaceA passed to doSomething method.

You need to either change it to a valid one:

class ConcreteA implements InterfaceC {
    public void doSomething(InterfaceA t)    {
        // Do something
    }
}

Above declaration doesn't prevent you from passing an object that implements InterfaceB as an argument, but the method declaration must match InterfaceC definition.

Or support with a generic type:

interface  InterfaceC &lt;T extends InterfaceA&gt;  {
     void doSomething(T t);
}

class ConcreteA implements InterfaceC&lt;InterfaceB&gt; {
    public void doSomething(InterfaceB t)    {
        // Do something
    }
}

huangapple
  • 本文由 发表于 2020年4月9日 18:46:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/61119364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定