【发布时间】:2013-01-06 16:09:46
【问题描述】:
这是场景 -> 假设有 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 类,以便它有一个方法可以做某事,但要求每个孩子都重写它?
- 如何强制子级(必须重写该方法)也调用父级的方法?
这几乎就像 Android 的 Activity 类具有 onCreate、onStart、onResume...等。方法是可选的,但如果你使用它,它会强制你调用 super.它不能是抽象的,因为我希望在调用方法时运行一些代码(仅在父类的方法中)。如果你知道他们是怎么做到的,可以加分吗?
【问题讨论】:
-
要强制覆盖函数调用其超类,请将此注释添加到超类中的函数:
@CallSuper。 Android Studio 会像onCreate一样给你提醒
标签: java android inheritance methods