gpt4 book ai didi

Java 泛型 - 遇到棘手的情况时遇到麻烦

转载 作者:行者123 更新时间:2023-12-01 17:32:56 25 4
gpt4 key购买 nike

我已经在这个问题上苦苦挣扎了好几个小时了,我已经把它提炼成一小段代码。你能看出错误在哪里吗?

public class Experiment {
class BaseMessage<Messageable> {
Messageable once;

BaseMessage(Messageable x) {
once = x;
}
}

class BaseEntity {
boolean handleMessage(BaseMessage<BaseEntity> theMessage) {
return false;
}

}

class StateMachine<Thing> {
public boolean handleMessage(BaseMessage<Thing> msg) {
return true;
}

}

class VehicleEntity extends BaseEntity {
public StateMachine<VehicleEntity> state;

@Override
boolean handleMessage(BaseMessage<VehicleEntity> theMessage) {
return state.handleMessage(theMessage);
}
}
}

我在这一行收到编译器错误:

boolean handleMessage(BaseMessage<VehicleEntity> theMessage) {

错误是:"The method handleMessage(Experiment.BaseMessage<Experiment.VehicleEntity>) of type Experiment.VehicleEntity must override or implement a super type method"

请注意,这是我的真实代码的示例子集,旨在将其减少到最小值,因此代码不会执行任何明智的操作。哇,如果你能弄清楚这一点,我将非常感激!

最佳答案

正如《悲惨变量》所述,在VehicleEntity中你有handleMessage(BaseMessage<VehicleEntity> theMessage)不是handleMessage(BaseMessage<BaseEntity> theMessage)并且编译器期望您的原始代码中使用后者。

主要的替代方案是 BaseEntity 采用“self”类型参数,如下所示:

class BaseEntity<T extends BaseEntity<T>> {
boolean handleMessage(BaseMessage<T> message) {
...
}
}
class VehicleEntity extends BaseEntity<VehicleEntity> {
boolean handleMessage(BaseMessage<VehicleEntity> message) {
...
}
}

关于Java 泛型 - 遇到棘手的情况时遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9270466/

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