• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Static or non static variable (for buttons)

robothito

Newbie
Hello and thanks always.
I have been reading tutorials about Android programming and I have the following question. In one tutorial the instructor used a private variable to hold a button (and other things such as EditTexts Radio buttons, etc) but in the next lesson- and without giving a reason - he used a private static variable.

Something like this:

Java:
public class MainActivity extends AppCompatActivity {

    private Button first_button;                  // Non static or
   private Static Button second_button;  //Static?

//some other code

public void listenerForButtons(){
           first_button=(Button)findViewById(R.id.button1);
       second_button=(Button)findViewById(R.id.button2);

//some more other code...
}
//etc

So I would like to ask which should I use? static or non static...?

Now I know the basic definition for static variables in classes in java. Class member variables vs Object member variables... you dont need to instantiate the class...

But in android?? Is MainActivity being instantiated?? I guess so because non static variables work fine.... but by who??

Any comment will be greatly appreciated
 
In this context it makes no sense to use the static modifier on a private class variable. It does no harm, but is redundant.

The normal use of static is to define a global constant value, which is visible from all classes. But that would require the variable to be declared 'public'.

An instance of MainActivity is created by the runtime framework when your app is started.
 
Why would you use a 'private static' class variable declaration? I can think of two scenarios:-

1. You had a private static class method which needed to access a class variable (static methods are only allowed to access static class variables)

2. You wanted to define a class variable which could be used statically between all instances of that class
 
Back
Top Bottom