gpt4 book ai didi

java - Android - 如何强制 child 覆盖具有代码的父方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:47 25 4
gpt4 key购买 nike

这是场景 -> 假设有 3 个类,我想做类似的事情:

public class GameObject {
public void updateBounds() {
// do something
}
}

public abstract class Enemy extends GameObject {
public abstract void updatePosition(){ //<-- this will not compile,
//but this is what i want to do, to force
//child to override parent method
updateBounds();
}

}

public class Minion extends Enemy {
@Override
public void updatePosition() {
super.updatePosition(); // <-- how do i throw an exception if this line
// is not called within this method of the
// child?
// now do something extra that only Minion knows how to do
}
}
  • 如何设计 Enemy 类,使它有一个方法可以做某事,但要求每个 child 都覆盖它?
  • 如何强制 child (必须重写该方法)也调用父方法?

这几乎类似于 Android 的 Activity 类,它具有 onCreate、onStart、onResume...等。方法是可选的,但如果你使用它,它会强制你调用 super.它不能是抽象的,因为我希望在调用方法时运行一些代码(仅在父类的方法中)。如果你知道他们是怎么做到的,可以加分吗?

最佳答案

Android 源代码使用一个名为 mCalled 的 boolean 值,它在准抽象方法实现中被设置为 true。在您的情况下,它将位于原始 updatePosition() 的内部。

然后当你想调用updatePosition()时,通过这样调用:

private void performUpdatePosition() {
mCalled = false;
updatePosition();
if (!mCalled) throw new SuperNotCalledException();
}

updatePosition() 看起来像这样

protected void updatePosition() {
mCalled = true;
updateBounds();
}

编辑:

现在我想起来了,android 做这件事的方式有点迂回。因为对 updatePosition() 的所有调用都通过 performUpdatePosition(),所以您不再需要在 updatePosition() 中包含一些代码被覆盖,但不应该。

更好的方法是将所需的操作简单地移动到performUpdatePosition():

private void performUpdatePosition() {
updateBounds();
updatePosition();
}

protected void updatePosition() {
//Do nothing by default
}

这样被调用者就不用担心调用super.updatePosition了。如果子类不覆盖该函数,则不会发生任何额外的事情,而如果他们这样做,覆盖将添加到以前的行为。

关于java - Android - 如何强制 child 覆盖具有代码的父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14475329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com