java泛型类层次结构和泛型实现

时间:2016-12-25 17:00:40

标签: java generics

这可能是一个愚蠢的问题,但我无法理解为什么以下编译失败。

我的班级层次结构

timer

这个Dao的通用实现

Dao.java

public interface Dao<E extends Entity, S extends SearchCriteria> {
    <E> E create(E e) throws Exception;
}

然后有专门的实施

DaoImpl.java

public abstract class DaoImpl<E extends Entity, S extends SearchCriteria> implements Dao<E, S> {
    @Override
    public <E> E create(E e) throws Exception {
        throw new UnsupportedOperationException("this operation is not supported");
    }
}

实体类层次结构的描述

ProcessDaoImpl.java

public class ProcessDaoImpl extends DaoImpl<Process, WildcardSearchCriteria> {
    @Override // this is where compilation is failing, I get the error that create doesn't override a superclass method
    public Process create(Process entity) throws Exception {
        return null;
    }
}

2 个答案:

答案 0 :(得分:5)

因为您应该在界面和抽象类中声明开头没有E create(E e)的{​​{1}}方法,否则您不会引用声明类型的<E>在类中,但是在方法范围内定义的E类型:

替换:

E

通过

 public interface Dao<E extends Entity, S extends SearchCriteria> {
    <E> E create(E e) throws Exception;
}

并替换为:

public interface Dao<E extends Entity, S extends SearchCriteria> {
     E create(E e) throws Exception;
}

by:

@Override
public <E> E create(E e) throws Exception {
    throw new UnsupportedOperationException("this operation is not supported");
}

答案 1 :(得分:2)

问题是:

<E> E create(E e) throws Exception;

E与类声明中的E不同E。您声明了一个 new 类型参数,其名称为E,没有限制,并且会从类中隐藏外部E create(E e) throws Exception;

将其更改为

initial-buffer-choice
相关问题