首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果我们在重写函数中编写super()函数之前或之后,代码的影响是什么?

如果我们在重写函数中编写super()函数之前或之后,代码的影响是什么?
EN

Stack Overflow用户
提问于 2015-08-30 14:56:36
回答 1查看 1.5K关注 0票数 6

我对overriden函数中的super()函数调用感到困惑。

代码语言:javascript
运行
复制
@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
}

在安卓系统中,在super.onDestroy()super.onPause()或其他超级函数之前或之后编写的代码会对所有类型的越权方法产生什么影响?

EN

回答 1

Stack Overflow用户

发布于 2015-08-30 17:39:20

一般来说,最好允许基类先初始化,最后销毁-这样,派生类所依赖的基类的任何初始状态都将首先得到排序,相反,任何派生类清理代码都可以依赖仍然有效的基类数据。

在Android中,我将这种行为扩展到onPauseonResume

代码语言:javascript
运行
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    // let Android initialise its stuff first
    super.onCreate();

    // now create my stuff now that I know any data I might
    // need from the base class must have been set up
    createMyStuff();
}

@Override
protected void onDestroy() {
    // destroy my stuff first, in case any destroying functionality
    // relies upon base class data
    destroyMyStuff();

    // once we let the base class destroy, we can no longer rely
    // on any of its data or state
    super.onDestroy();
}

@Override
protected void onPause() {
    // do my on pause stuff first...
    pauseMyStuff()        
    // and then tell the rest of the Activity to pause...
    super.onPause();
}

@Override
protected void onResume() {
    // let the Activity resume...
    super.onResume();
    // and then finish off resuming my stuff last...
    resumeMyStuff();
}

实际上,onPause()onResume()并没有真正受到订单的影响,因为它们对活动的状态几乎没有影响。但是,确保创造和毁灭遵循基地创造-第一,基础-摧毁-最后的顺序是极其重要的。

但是,规则的例外总是存在的,一个常见的例外是,如果要在onCreate()方法中以编程方式更改活动的主题,则必须在调用super.onCreate()之前进行更改。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32297862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档