1

Android 要求所有 Activity 子类从其生命周期方法中调用超级方法。如果未调用 super 方法,则会引发异常。为什么Android会使用RuntimeException机制来强制调用super方法。为什么它不使用“模板”设计模式,以便超级方法在子方法之前自动执行。例如 onDestroy() 可以按如下方式处理:-

Class Activity{

    public void onDestroyFrmwork()
    {
            //do whatever the super onDestroy() method has to do 
            onDestroy();//this will invoke the subclass method.
    }

    public void onDestroy()
    {
        //empty. will get overridden by subclasses.
    }
}
4

2 回答 2

2

我知道我在被问到这个问题 11 个月后才回答这个问题。我猜原因是不能提前确定调用super方法的顺序。例如,我可能想在调用之前super.onDestroy()、之后super.onDestroy()甚至混合起来之前进行清理,如下所示:

@Override
    protected void onDestroy() {
        // Do some initial clean-up
        preDestroy();

        //Then call super
        super.onDestroy();

        //In the end do some final clean-up
        postDestroy();

    }

这个例子是为了论证;但我敢肯定,如果你足够努力的话,你会遇到现实世界的例子。

使用模板设计模式很难实现这种混合排序。

于 2012-02-21T11:09:30.283 回答
0

如果您不调用超类方法,您的应用程序将无法正常工作,因此 API 会抛出 aRuntimeException以确保您不会忘记这样做。

于 2013-04-17T02:42:07.047 回答