泛型不起作用的覆盖方法(未找到方法) [英] Overriding method with generics not working (no method found)
问题描述
我正在尝试 @Override
类中的方法可能看起来像一个复杂的继承结构,但实际上它应该非常简单,但我无法得到它工作。
I am trying to @Override
a method in a class that might look like having a complex inheritance structure, but it should actually be quite simple, however I cannot get it to work.
public interface Action { }
public interface Result { }
public interface Player<A extends Action, R extends Result> {
default public <P extends Player<A, R>> void onPostAction(final P target, final A action, final R result) { }
}
abstract public class GesturePlayer<A extends Action, R extends Result> implements Player<A, R> { }
abstract public class RPSPlayer extends GesturePlayer<RPSGesture, RPSResult> { }
public class RPSHumanPlayer extends RPSPlayer {
@Override
public void onPostAction(final RPSPlayer target, final RPSGesture gesture, final RPSResult result) { }
}
我在 @Override
上收到错误 onPostAction
,为什么找不到正确的方法来覆盖?
I get the error on the @Override
of the onPostAction
, why can it not find the correct method to override?
这是针对Rock-Paper-剪刀实现让人想知道这个名字的来源。
This is for a Rock-Paper-Scissors implementation for people wondering where the name comes from.
确切的错误信息:
方法不会覆盖或实现超类型的方法
method does not override or implement a method from a supertype
我的目标是仍然使用当前的类,所以对于 RPSHumanPlayer
我实际上想要这个签名:
My goal is to still use the current class, so for RPSHumanPlayer
I would actually want to have this signature:
public void onPostAction(final RPSHumanPlayer target, final RPSGesture gesture, final RPSResult result) { }
推荐答案
Player
中的方法 onPostAction
本身就是通用的。您已经在那里定义了 P
。因此,任何覆盖它的方法也必须是通用的。
The method onPostAction
in Player
is itself generic. You have defined P
there. Therefore, any method that overrides it must also be generic.
尝试
public class RPSHumanPlayer extends RPSPlayer {
@Override
public <P extends Player<RPSGesture, RPSResult>> void onPostAction(final P target,
final RPSGesture gesture, final RPSResult result) { }
}
A
和 R
已由 GesturePlayer定义
要 RPSGesture
和 RPSResult
,但 P
仍然需要申报。
A
and R
are already defined by GesturePlayer
to be RPSGesture
and RPSResult
, but P
still needs to be declared.
加法
如果需要确切的话签名,然后你必须定义 P
以及 A
和 R $
播放器
界面上的c $ c>:
If it needs to be that exact signature, then you'll have to define P
along with A
and R
on the Player
interface:
public interface Player<A extends Action, R extends Result, P extends Player<A, R, P>> {
default public void onPostAction(final P target, final A action, final R result) { }
}
然后 GesturePlayer
相应更改:
abstract public class GesturePlayer<A extends Action, R extends Result,
P extends Player<A, R, P>> implements Player<A, R, P> { }
然后 RPSPlayer
将自己定义为 P
。
abstract public class RPSPlayer extends GesturePlayer<RPSGesture, RPSResult, RPSPlayer> { }
和 RPSHumanPlayer
可以有方法原样:
public class RPSHumanPlayer extends RPSPlayer {
@Override
public void onPostAction(final RPSPlayer target, final RPSGesture gesture, final RPSResult result) { }
}
这篇关于泛型不起作用的覆盖方法(未找到方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!