首页 > 解决方案 > 如何通过您正在扩展的类覆盖方法,同时仍在您正在覆盖的原始类中运行代码?

问题描述

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

在这个类中,我有一些样板代码来满足每个GameRoom实例的需要。

在单独的房间类中,我扩展了GameRoom类,覆盖了基类的updaterender方法GameRoom,但这使得我的瓷砖地图等无法呈现。

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

我怎么做?

标签: javaoop

解决方案


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"
  }
}

然后就可以调用模板方法来运行程序了,模板方法只有父类定义,它会调用子类的钩子方法,这些方法都必须实现。


推荐阅读