java - 非泛型类可以实现泛型接口(interface)吗?

标签 java generics interface

我一直在阅读 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/

相关文章:

java - 接口(interface)的变量在JAVA中是如何工作的,如何调用接口(interface)的方法?

java - Tomcat 在生产服务器上突然停止工作

java - Python:指定相同的通用参数类型

c# - 将 Null 转换为 Nullable 枚举(通用)

java - 是否可以在接口(interface)中使用 setLayout() 以便 "force"实现类以使用特定布局?

interface - 满足隐式接口(interface)而无需重新实现的记录

java - 具有动态类型字段的对象

java - 我在ubuntu中使用maven,.java,sts eclipse和selenium ide,svn和web驱动程序

java - 如果唯一键匹配,则跳过持久化实体

c# - C#泛型中Java通配符的等价物是什么