如何通过您正在扩展的类重写方法,同时仍在您要重写的原始类中运行代码?

我有一个游戏系统,其基类名为GameRoom.

在本课程中,我有一些适合每个GameRoom实例所需的样板代码。

在各个房间类中,我扩展了该类GameRoom,覆盖了基类的update和方法,但这使得我的图块地图等无法渲染。renderGameRoom

我希望样板代码保持渲染,同时能够在子GameRoom类中运行自定义代码(具有完全相同的名称)。

我怎么做?



森栏
浏览 80回答 2
2回答

天涯尽头无女友

您可以使用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"  }}然后你可以通过调用模板方法来运行程序,该方法仅由父类定义,并且它会调用子类的钩子方法,子类都必须实现这些方法。

函数式编程

如果你有类似的东西:abstract class Room{    abstract void render(Canvas c){        //impl goes here    }}然后在你的子类中你可以这样做:class SpecificRoom extends Room{    void render(Canvas c){        super.render(c);//calls the code in Room.render    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java