gpt4 book ai didi

java - 为什么我不能使用泛型类型来实现非泛型签名

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

我对 Java 编译器有点困惑。

我有一个带有“Object”方法签名的接口(interface):

public interface Bean {
public void setCreated(final Object created);
}

我想用一个泛型来实现它:

public class BeanImpl<T extends Object> implements Bean{
private T created;

public void setCreated(final T created){
this.created = (T)created;
}
}

但是,这会产生一个编译器错误:

Name clash: The method setCreated(T) of type BeanImpl<T> has the same erasure as setCreated(Object) of type Bean but does not override it

鉴于根据定义,T 是一个 Object (),为什么编译器不允许我进行此构造?尝试将其标记为 @Override 只会产生一条错误消息,表明该方法实际上并未覆盖父类(super class)型。就好像编译器不理解/看不到 T 实际上是一个对象。

最佳答案

如果允许,那么有人可能会创建

public class Child extends BeanImpl<Integer> {
public void setCreated(Integer created){
// whatever
}
}

Bean bean = new Child();
bean.setCreate(new NotAnInteger());

并且类型安全会被破坏。你必须满足接口(interface)。

关于java - 为什么我不能使用泛型类型来实现非泛型签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26002393/

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