Guy
Guy

Reputation: 13306

What is the difference between declaring a final variable in an Activity and instantiating it on the onCreate method?

This:

public class LoadingActivity extends Activity  {

      final private ContactManager cm = new ContactManager(this);
      ...

vs. this:

public class LoadingActivity extends Activity {

    private ContactManager cm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_loading);
       cm = new ContactManager(this);
       ...

I understand the meaning of final, the variable would not be able to re-instantiate, however I am not sure which pattern to use and how this affects the Garbage Collector? I guess that on the 2nd version I can use onDestroy to notify the Garbage Collector that I am done with the variable. Does that make sense? Is that needed at all?

Upvotes: 0

Views: 70

Answers (3)

OneCricketeer
OneCricketeer

Reputation: 191728

Generally speaking, in Java, it isn't good to use this until you have an instance to work with. Using a constructor is the recommended way for method one, but Activity constructors aren't used that way, so pattern 2 is correct in terms of Android code.

If you need to make the variable final, you'd need to wrap it in another Java class where you can properly initialize the variable with a constructor.

Upvotes: 1

Ankesh kumar Jaisansaria
Ankesh kumar Jaisansaria

Reputation: 1591

In first case, you have declared cm variable as final, So you cannot define any new value to this variable. i.e now you cannot write cm = xyz.

In second case you can anytime change the value of cm or reinitialize it with some parameters etc.

In your case second method will work best

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006744

In the specific case of Android component classes (e.g., Activity, Service), only use the final-plus-initializer approach for cases where you do not need this. Methods inherited from the base classes for those components (e.g., Activity) may not work until after super.onCreate() is called from the onCreate() method.

Hence, in your two examples shown above, the second one is correct.

Upvotes: 2

Related Questions