Is it possible to implement an interface for multiple choices of its generic parameters? For example, if I have an interface
public interface MyInterface<T> {
T doSomething(T);
}
and then a class implementing it for multiple choices of T? For example
public class MyClass implements MyInterface<SomeClass>, MyInterface<SomeOtherClass> {
SomeClass doSomething(SomeClass T) {
//here the implementation
}
SomeOtherClass doSomething(SomeOtherClass T) {
//here the implementation
}
}
The above doesn’t work, so how should this be done properly in Java?
I don’t think there’s a way to get this to work, as there are plenty of good reasons why it shouldn’t work, but depending on what exactly your use-case is, there might be ways to work around it. For example:
And remembering that you can use
<? super SomeClass>or<? extends SomeClass>can also sometimes help with issues like this.