[英]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. 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?
有没有办法在覆盖方法中指定 class A 和 Class B ?
I tried below:我在下面试过:
Class ConverterImpl implements Converter{
@Override
B convert(A a){
//...
}
}
I tried above, it has compile error says not implement convert method我在上面试过了,它有编译错误说没有实现转换方法
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.使用您的方法声明,每个 class 都需要实现通用版本。
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)
.在这种情况下,这将是
Function<T,R>
与方法R accept(T)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.