Member object instantiation in onCreate vs. during

2019-07-28 17:51发布

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

and

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.

2条回答
乱世女痞
2楼-- · 2019-07-28 18:27

An Activity has a well defined lifecycle, as you probably know. It does not always matter if you create new instances in the constructor vs. onCreate, but you would definitely prefer onCreate in these circumstances:

  1. If the new object requires a valid Context, that is not available until onCreate(). You can't do this in the constructor.
  2. If you wish to proactively release the resource as soon as you don't need it any more, onDestroy provides a nice analog to onCreate with respect to the activity lifecycle. This may help objects be reclaimed faster than they would if they were created in the constructor and stored as "final". While this is not strictly necessary, it makes it clear to the reader that you wish to do work following the lifecycle of the Activity, not just the with the object instance itself.
查看更多
欢心
3楼-- · 2019-07-28 18:33

Functionally, nothing.

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.

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

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

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).

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

查看更多
登录 后发表回答