onCreate 中的成员对象实例化与声明期间的成员对象实例化 [英] Member object instantiation in onCreate vs. during declaration

查看:32
本文介绍了onCreate 中的成员对象实例化与声明期间的成员对象实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在询问这两种方法之间的区别:

I am basically asking about the difference between these two approaches:

public class myClass extends AppCompatActivity {
    private objectType mObject = new objectType();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //do stuff with mObject

public class myClass extends AppCompatActivity {
    private objectType mObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mObject = new ObjectType();

我希望我说得够清楚了.我很难理解我们什么时候想要选择一个而不是另一个.

I hope I'm being clear enough. I am struggling to understand when we'd want to choose one versus the other.

推荐答案

功能上,没什么.

第一个将在创建 Activity 对象时创建(调用new myClass()).Android 系统会在创建过程中的某个时刻执行此操作.

The first one will be created when the Activity object is created (new myClass() is called). The Android system does this at some point during creation.

当系统最终调用 onCreate() 时,将创建第二个.

The second one will be created when the system eventually calls onCreate().

问题在于,如果您有一个在构造函数中需要 Context 的对象.例如,您可以这样做:

The gotcha would be if you had an object that needs a Context in the constructor. You could do this for example:

public class myClass extends AppCompatActivity {
    private objectType object = new objectType(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //do stuff with object

应用程序会突然崩溃,因为您很可能会尝试从尚不存在的 Context 中提取资源.(请记住,此时尚未创建 Activity).

And the app will suddenly crash because you most likely will try to extract resources from the Context that don't exist yet. (Remember, the Activity isn't created at this point).

因此,如果您的对象确实必须使用 Context,那么您必须在调用 onCreate 时或之后创建它.

So, if your object does have to use Context, then you have to create it at or after onCreate is called.

这篇关于onCreate 中的成员对象实例化与声明期间的成员对象实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆