views:

69

answers:

2

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  A: 

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 : alt text

Colin Hebert
+3  A: 

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) { .. }
}
Marc
This might well be the solution.... Thanks for the practical advice.
badpanda
Actually, this causes the same error.
badpanda
What version of Java are you using? In Java 1.6 under Eclipse this works correctly.
Marc
@badpanda, that's because you implemented twice the same interface
Colin Hebert