java - 如何通过您正在扩展的类覆盖方法,同时仍在您正在覆盖的原始类中运行代码?
问题描述
我有一个游戏系统,其基类名为GameRoom
.
在这个类中,我有一些样板代码来满足每个GameRoom
实例的需要。
在单独的房间类中,我扩展了GameRoom
类,覆盖了基类的update
和render
方法GameRoom
,但这使得我的瓷砖地图等无法呈现。
我希望样板代码保持渲染,同时能够在子类中运行自定义代码(具有完全相同的名称)GameRoom
。
我怎么做?
解决方案
super
您可以通过使用而不是调用重写的方法this
。
class Example extends Parent {
@Override
void method() {
super.method(); // calls the overridden method
}
}
如果您想强制每个子类调用父类的方法,Java 没有为此提供直接机制。但是您可以使用调用抽象函数的最终函数来允许类似的行为(模板方法)。
abstract class Parent {
final void template() { // the template method
System.out.println("My name is " + this.nameHook());
}
protected abstract String nameHook(); // the template "parameter"
}
class Child {
@Override
protected String nameHook() {
return "Child"
}
}
然后就可以调用模板方法来运行程序了,模板方法只有父类定义,它会调用子类的钩子方法,这些方法都必须实现。
推荐阅读
- python - 如何获取导致 dask.read_csv 错误的 csv 文件的名称?
- python - 没有空格的字符串需要根据模式拆分
- c# - Elasticsearch NEST 和基本搜索查询
- xamarin - 如果将 Xamarin 条目移除并添加到父视图,则 Xamarin 条目将获得焦点。为什么会这样?
- java - jar 文件有时不会从网络共享启动
- python - 如何更改熊猫数据框图上的 Y 轴
- python - 如何比较具有不同频率的2个文件的时间戳
- matlab - 预期大括号或点索引表达式有一个输出,但有 2 个结果。matlab
- reactjs - 在 ReactJS 中设置后不显示状态
- sql - 将两个查询加入两列