ski*_*iwi 6 java inheritance overriding
我正在尝试@Override一个类似于具有复杂继承结构的类中的方法,但它实际上应该非常简单,但是我不能让它工作.
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) { }
}
Run Code Online (Sandbox Code Playgroud)
我得到了错误@Override的onPostAction,它为什么不能找到正确的方法重写?
这是针对Rock-Paper-Scissors的实现,让人们想知道这个名字的来源.
确切的错误消息:
方法不会覆盖或实现超类型的方法
我的目标是仍然使用当前的类,所以RPSHumanPlayer我真的想要这个签名:
public void onPostAction(final RPSHumanPlayer target, final RPSGesture gesture, final RPSResult result) { }
Run Code Online (Sandbox Code Playgroud)
onPostAction中的方法Player本身是通用的。你已经P在那里定义了。因此,任何重写它的方法也必须是通用的。
尝试
public class RPSHumanPlayer extends RPSPlayer {
@Override
public <P extends Player<RPSGesture, RPSResult>> void onPostAction(final P target,
final RPSGesture gesture, final RPSResult result) { }
}
Run Code Online (Sandbox Code Playgroud)
A和R已由GesturePlayertoRPSGesture和定义RPSResult,但P仍需要声明。
添加
如果需要精确的签名,那么您必须在接口上P定义:ARPlayer
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) { }
}
Run Code Online (Sandbox Code Playgroud)
然后GesturePlayer进行相应的更改:
abstract public class GesturePlayer<A extends Action, R extends Result,
P extends Player<A, R, P>> implements Player<A, R, P> { }
Run Code Online (Sandbox Code Playgroud)
然后RPSPlayer将自己定义为P.
abstract public class RPSPlayer extends GesturePlayer<RPSGesture, RPSResult, RPSPlayer> { }
Run Code Online (Sandbox Code Playgroud)
并且RPSHumanPlayer可以有这样的方法:
public class RPSHumanPlayer extends RPSPlayer {
@Override
public void onPostAction(final RPSPlayer target, final RPSGesture gesture, final RPSResult result) { }
}
Run Code Online (Sandbox Code Playgroud)