在Java中继承泛型接口

时间:2016-10-28 12:24:55

标签: java generics interface

我有与泛型的接口:

public interface Cache<CachePrimaryKey extends Object, RowModel extends CacheRowModel>

我需要创建扩展Cache的子接口,但在保留泛型的同时添加新方法。保留泛型部分的正确语法是什么?

我有类似的实现。

public class InfoCache implements Cache<Long, DataRowModel> 

我试过

public interface EnrichedCache<CachePrimaryKey extends Object, 
       RowModel extends CacheRowModel> extends  Cache

但是当我将InfoCache-class的接口从Cache更改为EnrichedCache时,我得到的是#34;不会覆盖其超类&#34;中的方法。如果我使用&#34;实施方法&#34;在IntelliJ中,它不是Long + DataRowModel的方法,而是为Object和CacheRowModel提供方法(这不是我想要的)。

继承接口和保留所有泛型的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

首先,我们使用大写字母来表示泛型,这是为了避免以下废话:

public interface Cache<String> {
    String getKey();
}

上面interface做了什么?

所以,将interface重写为:

public interface Cache<K, R extends CacheRowModel>

请注意extends Object是废话,我已将其删除

然后创建interface extends Cache的通用public interface EnrichedCache<K, R extends CacheRowModel> extends Cache<K,R> 并保留相同的泛型:

interface

即。我们有一个通用的K,其参数R(可以是任何内容)和CacheRowModel(必须是extends Cache的子类)public interface NumericCache<K extends Number, R extends CacheRowModel> extends Cache<K,R> 具有相同的参数

您也可以收紧传递的仿制品:

NumericCache

此处我们需要extends Numberpublic interface StringCache<R extends CacheRowModel> extends Cache<String, R> 的密钥。

您还可以将一个通用参数设置为具体类型,然后传递第二个参数:

String

这里我们将继承缓存的密钥显式设置为CacheRowModel,但允许用户指定要使用的{{1}}。

答案 1 :(得分:0)

您的第二个界面扩展了原始缓存。

试试这段代码:
public interface EnrichedCache<CachePrimaryKey extends Object, RowModel extends CacheRowModel> extends Cache<CachePrimaryKey, RowModel>