Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable across multiple, different subclasses - corrected

I was wondering what happened if I define a base Activity object with all my activities as subclasses of that. Then I declare a static variable in the base class, will all the subclasses use the SAME static or will there be one per subclass.

For example. My base class:

public class MyBaseActivity extends Activity{

   static int myStatic;

   ... 
   ....

}

Then:

public class MyActivity1 extends MyBaseActivity {


   private void someMethod1(){
         myStatic = 1;
    }

   ... 
   ....

}

and

public class MyActivity1 extends MyBaseActivity {

   private void someMethod2(){
          if (myStatic == 1)
            doSomething();
    }

   ... 
   ....

}

If I now start MyActivity1 and it sets a value in "myStatic". It then exits and then I start MyActivity2 - should I still have the value set by the first activity? In the example above, would the "if" statement be true or false?

I know that if I instantiate Activity1 more than once then obviously I would get the same static variable. However, here I am instantiating a different subclass each time.

I am getting the impression that that is what is happening to me but want to be sure.

like image 528
theblitz Avatar asked Jun 02 '11 14:06

theblitz


People also ask

Are static variables shared between subclasses?

Static Variables: When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.

Can static variables be edited?

Static methods cannot access or change the values of instance variables, but they can access or change the values of static variables.

Why static variables are evil?

Static variables are generally considered bad because they represent global state and are therefore much more difficult to reason about. In particular, they break the assumptions of object-oriented programming.

Do static variables stay the same?

Yes, static values will remain same for all users. if one user is updating that value, then it will be reflected to other users as well.


1 Answers

Static is static. They will reference the same object.

like image 189
Haphazard Avatar answered Sep 23 '22 06:09

Haphazard