在使用泛型(Java)的扩展接口中覆盖方法合约? [英] Overriding a method contract in an extended interface that uses generics (Java)?

查看:103
本文介绍了在使用泛型(Java)的扩展接口中覆盖方法合约?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


InterfaceExtended中的myMethod(T)
与Interface中的myMethod(T)发生冲突;
这两种方法都有相同的擦除操作,
但是不会覆盖另一个。

代码如下所示: / p>

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

public interface ExtendedInterface< T>扩展Interface< T>
{
public void myMethod(T x);

$ / code>

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



谢谢!

badPanda

解决方案

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

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

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

$ / code>

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

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

编辑:有趣的是,这也行得通(尽管它没用):

  class MyClass实现ExtendedInterface< String,String> {
public void myMethod(String 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

解决方案

Do you want an overloaded version of myMethod? Then you should not use T twice, but like this:

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

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

Now it is possible to have something like this:

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

Edit: interestingly enough, this also works (although it is useless):

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

这篇关于在使用泛型(Java)的扩展接口中覆盖方法合约?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆