java方法泛型实现接口 [英] java method generics implementing interface
问题描述
这段代码有什么问题?
public interface FileProccessor {
public< RT> RT setHeader(RT头);
公共类AProcessor实现FileProccessor {
@Override
public Header setHeader(Header header){
return null;
Compilator抱怨说:方法setHeader头部)类型的AProcessor必须重写或实现超类型方法 b 编辑: 声明指定接口的所有实现都将为此签名提供一个通用方法: 换句话说,调用者可以传递任何类型的对象,然后取回另一方面,您的实现声明将用户限制为单一类型,即 如果接口是通用接口,并且实现它的类型实现了一个通用实例, What is wrong with this code? Compilator is complaining: The method setHeader(Header) of type AProcessor must override or implement a supertype method Edit:
Thanks. I got confused because I wanted multiple methods with different types.
Now I realized a can add as many parametrized types as I want in class level. Like Your interface declaration specifies that all implementations of the interface will provide a generic method with this signature: In other words, the caller would be able to pass an object of any type, and get back an object of the same exact type. You implementation declaration, on the other hand, limits the user to a single type, i.e. the The trick would work if the interface were generic, and a type implementing it was implementing a generic instance, like this:
这篇关于java方法泛型实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b
谢谢。我很困惑,因为我想要多种不同类型的方法。
现在我意识到可以在课堂级别添加尽可能多的参数化类型。与 FileProcessor< T,F,M>
。
public< RT> RT setHeader(RT头);
Header 。 code>。这就是为什么编译器抱怨无法覆盖。
public interface FileProccessor< T> {
public T setHeader(T header);
}
公共类AProcessor实现FileProccessor< Header> {
}
public interface FileProccessor {
public <RT> RT setHeader(RT header);
}
public class AProcessor implements FileProccessor {
@Override
public Header setHeader(Header header) {
return null;
}
}
FileProcessor<T, F, M>
.public <RT> RT setHeader(RT header);
Header
. That's why the compiler is complaining about inability to override.public interface FileProccessor<T> {
public T setHeader(T header);
}
public class AProcessor implements FileProccessor<Header> {
}