user1111929
user1111929

Reputation: 6099

implement interface with different generics?

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?

Upvotes: 0

Views: 97

Answers (1)

Joe K
Joe K

Reputation: 18434

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:

public class MyClass implements MyInterface<Object> {

    Object doSomething(Object T) {
        if (T instanceof SomeClass) {
            doSomethingSomeClass((SomeClass)T);
        } else if (T instanceof SomeOtherClass) {
            doSomethingSomeOtherClass((SomeOtherClass)T) {
        } else {
            // handle other objects - return null? throw exception?
        }
    }

    SomeClass doSomethingSomeClass(SomeClass T) {
        //here the implementation
    }

    SomeOtherClass doSomethingSomeOtherClass(SomeOtherClass T) {
        //here the implementation
    }
}

And remembering that you can use <? super SomeClass> or <? extends SomeClass> can also sometimes help with issues like this.

Upvotes: 1

Related Questions