开发者

Static variable across multiple, different subclasses - corrected

开发者 https://www.devze.com 2023-03-09 20:34 出处:网络
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 subclasse

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.


Static is static. They will reference the same object.


Static variables belong to the Class object, not instances. There is only one Class object (for that class), so there is only one instance of the static variable, so "yes they all see the same variable".

Subclasses have visibility of the variable if it's protected or public.


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?

All subclass will share the same static class instance. so the if statement is true

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号