gpt4 book ai didi

java - 在使用泛型(Java)的扩展接口(interface)中覆盖方法契约?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:57:48 25 4
gpt4 key购买 nike

我正试图覆盖扩展另一个接口(interface)的接口(interface)中的方法声明。这两个接口(interface)都使用泛型。根据 Java 教程,这应该是可能的,但该示例未使用泛型。当我尝试实现它时,编译器显示以下错误(我已经替换了名称,因为有些代码不是我自己的。):

myMethod(T) in InterfaceExtended clashes with myMethod(T) in Interface; both methods have the same erasure, but neither overrides the other.

代码如下所示:

public interface Interface<T>
{
public void myMethod(T x);
}

public interface ExtendedInterface<T> extends Interface<T>
{
public void myMethod(T x);
}

如果有人对如何改变它以使其可接受有任何建议,或者对这导致问题的原因有任何解释,我将非常感激。

谢谢!

坏 Pandas

最佳答案

您想要重载版本的 myMethod 吗?那么你不应该使用 T 两次,而是像这样:

public interface Interface<T>
{
public void myMethod(T x);
}

public interface ExtendedInterface<T, V> extends Interface<T>
{
public void myMethod(V x);
}

现在可以有这样的东西了:

class MyClass implements ExtendedInterface<String, Integer> {
public void myMethod(String x) { .. }
public void myMethod(Integer x) { .. }
}

编辑:有趣的是,这也有效(尽管没用):

class MyClass implements ExtendedInterface<String, String> {
public void myMethod(String x) { .. }
}

关于java - 在使用泛型(Java)的扩展接口(interface)中覆盖方法契约?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com