为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森栏 2023-07-28 16:10:34
我有一个游戏系统,其基类名为GameRoom.在本课程中,我有一些适合每个GameRoom实例所需的样板代码。在各个房间类中,我扩展了该类GameRoom,覆盖了基类的update和方法,但这使得我的图块地图等无法渲染。renderGameRoom我希望样板代码保持渲染,同时能够在子GameRoom类中运行自定义代码(具有完全相同的名称)。我怎么做?
查看完整描述

2 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

您可以使用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"

  }

}

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


查看完整回答
反对 回复 2023-07-28
?
函数式编程

TA贡献1807条经验 获得超9个赞

如果你有类似的东西:


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

    }

}


查看完整回答
反对 回复 2023-07-28
  • 2 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信