1. Are you ready for the Galaxy S20? Here is everything we know so far!

Static or non static variable (for buttons)

Discussion in 'Android Development' started by robothito, Feb 17, 2016.

  1. robothito

    robothito Newbie
    Thread Starter

    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:

    Code (Java):
    1. public class MainActivity extends AppCompatActivity {
    2.  
    3.     private Button first_button;                  // Non static or
    4.    private Static Button second_button;  //Static?
    5.  
    6. //some other code
    7.  
    8. public void listenerForButtons(){
    9.            first_button=(Button)findViewById(R.id.button1);
    10.        second_button=(Button)findViewById(R.id.button2);
    11.  
    12. //some more other code...
    13. }
    14. //etc
    15.  
    16.  
    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
     


  2. Deleted User

    Deleted User Guest

    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.
     
  3. Deleted User

    Deleted User Guest

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

Share This Page

Loading...