dylan7 dylan7 - 3 years ago 150
Android Question

Android Activity Variable types

In the android main activity I have seen two type of variables: instance variables declared at the top, and what seems like global variables also declared at the top, because they are not referenced through the activity using "this" and do not have a static qualifier. Why are instance variables used sometimes and these what seem to be "global" variables used other times? Which is better to use? They both seem to act global in a sense, since I believe there is just one MainActivity instance created.

Answer Source

If a field is not declared static, it is not static. Instance fields can be used with or without this, so instanceField and this.instanceField can both be used.

You should use instance fields for values that belong to individual instances of the class. static fields do not belong to individual instances.

It is possible for there to exist multiple instances of the same Activity class at once, depending on how your app works. For many apps, this is not possible, and in this case the difference between instance and static fields is academic to some extent. In this case, I tend to use instance fields for mutable state and static fields for constants, such as static final int NUMBER_OF_LEVELS = 60;.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download