Overriding a method contract in an extended interface that uses generics (Java)?

杀马特。学长 韩版系。学妹 提交于 2019-12-07 17:07:18

问题


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


回答1:


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) { .. }
}



回答2:


This does work. You could have a problem if your class implements twice the same interface with two different generics types.

For example :

class MyClass implements Interface<String>, ExtendedInteface<Integer>{
}

For example this code only fails on the third class.

And here is the message I have on IntelliJ X :



来源:https://stackoverflow.com/questions/3961639/overriding-a-method-contract-in-an-extended-interface-that-uses-generics-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!