现在,我已经把头撞在墙上的墙上好几个小时了,我已经将其精炼为一小段代码。您能看到错误在哪里吗?
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"
请注意,这是我的真实代码的示例子集,可将其减少到最低限度,因此代码不会做任何明智的事情。哇,如果您能解决这个问题,我将不胜感激!
最佳答案
如Miserable Variable所述,在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 - Java泛型-遇到棘手的情况,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9270466/