作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正试图覆盖扩展另一个接口(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/
我是一名优秀的程序员,十分优秀!