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

时间:2019-09-14 22:22:51

标签: java oop

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

在此类中,我为每个GameRoom实例需要的内容提供了一些样板代码。

在各个房间类中,我扩展了GameRoom类,覆盖了基础update类的renderGameRoom方法,但这使我的tilemap等无法渲染。

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用super而不是this来调用覆盖的方法。

class Example extends Parent {
  @Override
  void method() {
    super.method(); // calls the overridden method
  }
}

如果要 force 强制每个子类从父类中调用方法,Java不会为此提供直接机制。但是您可以使用最终函数来调用抽象函数以允许类似的行为(template method)。

abstract class Parent {
  final void template() { // the template method
    System.out.println("My name is " + this.getName());
  }
  protected abstract String nameHook(); // the template "parameter"
}

class Child {
  @Override
  protected String nameHook() {
    return "Child"
  }
}

然后,您可以通过调用仅由父类定义的模板方法来运行程序,并且它将调用子类的钩子方法,它们都必须已实现。

答案 1 :(得分:1)

如果您有类似的东西:

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