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

余生长醉 提交于 2019-12-06 01:38:55

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

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 :

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