重写使用泛型(Java)的扩展接口中的方法契约?
我试图重写扩展另一个接口的接口中的方法声明。这两个接口都使用泛型。根据 Java 教程,这应该是可能的,但该示例没有使用泛型。当我尝试实现它时,编译器显示以下错误(我替换了名称,因为某些代码不是我自己的。):
接口扩展中的 myMethod(T) 与接口中的 myMethod(T) 冲突; 两种方法具有相同的擦除功能, 但两者都不覆盖另一个。
代码如下所示:
public interface Interface<T>
{
public void myMethod(T x);
}
public interface ExtendedInterface<T> extends Interface<T>
{
public void myMethod(T x);
}
如果有人对如何更改此代码以使其可以接受有建议,或者对导致问题的原因有解释,我将非常感激。
谢谢!
坏熊猫
I am attempting to override a method declaration within an interface that extends another interface. Both of these interfaces use generics. According to the Java tutorials, this should be possible, but the example does not use generics. When I try to implement it, the compiler shows the following error (I've replaced names because some of the code is not my own.):
myMethod(T) in InterfaceExtended
clashes with myMethod(T) in Interface;
both methods have the same erasure,
but neither overrides the other.
Code looks like this:
public interface Interface<T>
{
public void myMethod(T x);
}
public interface ExtendedInterface<T> extends Interface<T>
{
public void myMethod(T x);
}
If anyone has suggestions as to how to alter this to make it acceptable, or an explanation regarding the reason this is causing a problem, I would very much appreciate it.
Thanks!
badPanda
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要 myMethod 的重载版本吗?那么你不应该使用 T 两次,而是像这样:
现在可以有这样的东西:
编辑:有趣的是,这也有效(尽管它没用):
Do you want an overloaded version of myMethod? Then you should not use T twice, but like this:
Now it is possible to have something like this:
Edit: interestingly enough, this also works (although it is useless):
这确实有效。如果您的类使用两种不同的泛型类型实现了两次相同的接口,则可能会出现问题。
例如:
此代码仅在第三类上失败。
这是我在 IntelliJ X 上收到的消息:
This does work. You could have a problem if your class implements twice the same interface with two different generics types.
For example :
For example this code only fails on the third class.
And here is the message I have on IntelliJ X :