gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:17 24 4
gpt4 key购买 nike

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

我的类(class)结构

Dao.java

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

这个 Dao 有一个通用的实现

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;
}
}

实体类层次结构说明

Process.java

public class Process extends AuditEntity {
// some pojo fields
}

AuditEntity.java

public abstract class AuditEntity extends IdentifiableEntity {
// some pojo fields
}

IdentifiableEntity.java

public abstract class IdentifiableEntity extends Entity {
// some pojo fields
}

Entity.java

public abstract class Entity implements Serializable {
}

最佳答案

因为你应该在接口(interface)和抽象类中声明,E create(E e)没有 <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;
}

并替换它:

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

作者:

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

关于java泛型类层次结构和泛型实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com