具有继承的Java接口

时间:2011-11-18 19:16:10

标签: java generics

我正在寻求有关如何实施此存储库的帮助。这是我到目前为止所做的:

public interface IEntity {
    int getId(); //would rather not depend on int. fix later.
}

public interface IRepository<T extends IEntity> {

    Collection<T> findAll();
    T find(T t);
    T findById(int id); //would rather not depend on int. fix later.
    void add(T t);
    void remove(T t);
}

public interface ISurveyRepository extends IRepository<Survey> {

}

我遇到的问题是我需要T签名中的IRepository扩展IEntity,但IRepositoryISurveyRepository不需要public interface ISurveyRepository extends IRepository { } {1}}签名具有有界类型参数。我希望签名只是

ISurveyRepository

这样我就可以创建一个只实现public class MySurveyRepository extends ISurveyRepository { }

的具体类
{{1}}

我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

如果你想创建一个类:

public class MySurveyRepository extends ISurveyRepository {}

然后你现有的界面(使用泛型)就可以了。您的实现类将通过设计“继承”该定义,并且(有效地)完全不知道它来自先前通用的接口。

如果您正在使用其中一个现代编辑器(如Eclipse)来编写代码,当您要求它填写缺少的继承方法时,它将不会为您提供T - 它会给您Survey

答案 1 :(得分:1)

你可以比这更好。

立即修复int问题。使用通用DAO接口,如下所示:

public interface Repository<T, K extends Serializable> {
    List<T> find();
    T find(K id);
    K save(T value);
    void update(T value);
    void delete(T value);    
}

伪装匈牙利符号:“接口”没有“我”。

您也可以编写通用实现。

相关问题