我一直在阅读 Herbert Schildt 的“Java。初学者指南”。在一页的通用接口(interface)部分,作者写道(强调我的):
Any class that implements a generic interface must itself be generic.
在下一页(强调我的):
In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface.
那么在Java中有没有非泛型类可以实现泛型接口(interface)的特定情况呢?或者所有这些类都是通用的,因为它们从通用接口(interface)“继承”了通用性?
UPD:我应该进一步阅读该部分。作者接着说:
Of course, if a class implements a specific type of generic interface, such as shown here:
class MyClass implements Containment<Double> {
then the implementing class does not need to be generic.
我相信,这是我的帖子的所有答案的要点。
最佳答案
只要提供了类型参数,就可以创建实现通用接口(interface)的非通用类。
一个相对简单的例子:
public class LocalDateParser implements Function<String, LocalDate> {
public LocalDate apply (String s) {
return LocalDate.parse(s);
}
}
当然,你只能将这个类的一个实例赋值给Function<String, LocalDate>
,而不是任何其他Function<T, R>
.
关于java - 非泛型类可以实现泛型接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54316272/