asker11
asker11

Reputation: 3

How to override a method with generic type

I need to override a generic method like below:

interface Converter{
    <S, T> T convert(S s);
}

Now I have Class A and Class B, I want to override above method by convert Class A object to Class B object. I did like below but all show error not implement the method. Is there a way I can specify the class A and Class B in the override method?

I tried below :

Class ConverterImpl implements Converter{
    @Override
    B convert(A a){
        //...
    }
}

I tried above, it has compile error says not implement convert method

Upvotes: 0

Views: 71

Answers (1)

daniu
daniu

Reputation: 14999

I think what you want is generify the interface.

interface Converter<T,R> {
   R convert(T toConvert);
}

and you implement it with

class AtoBConverter implements Converter<A,B> {
   B convert(A toConvert);
}

With your method declaration, each class would need to implement the generic version.

BTW it is usually good practice to use existing interfaces; in this case, this would be Function<T,R> with the method R accept(T).

Upvotes: 1

Related Questions