跨多个不同的子类的静态变量 - 更正多个、子类、变量、静态

2023-09-07 16:40:35 作者:夜幕篱下浅笙歌°

我不知道发生了什么事,如果我定义我的所有活动的子类基本活动对象。然后,我宣布在基类中的静态变量,将所有的子类使用同一个静态或会有每个子类之一。

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.

例如。我的基类:

public class MyBaseActivity extends Activity{

   static int myStatic;

   ... 
   ....

}

然后:

public class MyActivity1 extends MyBaseActivity {


   private void someMethod1(){
         myStatic = 1;
    }

   ... 
   ....

}

public class MyActivity1 extends MyBaseActivity {

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

   ... 
   ....

}

如果我现在开始MyActivity1并将其设置在myStatic值。然后,它退出,然后我开始MyActivity2 - 我应该还是有通过的第一个活动设置的值?在上面的例子中,将在if语句是真的还是假的?

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?

我知道,如果我实例化活性1不止一次那么显然我会得到相同的静态变量。不过,我在这里,每次实例化一个不同的子类。

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.

我收到IM pression那是什么发生在我身上,但要确保。

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.