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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6215680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:53:22  来源:igfitidea点击:

Static variable across multiple, different subclasses - corrected

javaandroidstatic

提问by theblitz

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.

我想知道如果我定义一个基本 Activity 对象并将我的所有活动作为它的子类会发生什么。然后我在基类中声明一个静态变量,所有子类都使用相同的静态变量还是每个子类都有一个。

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?

如果我现在启动 MyActivity1 并在“myStatic”中设置一个值。然后它退出,然后我启动 MyActivity2 - 我应该仍然拥有第一个活动设置的值吗?在上面的例子中,“if”语句是对还是错?

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.

我知道如果我多次实例化 Activity1 那么显然我会得到相同的静态变量。但是,在这里我每次都实例化一个不同的子类。

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

我得到的印象是这就是发生在我身上的事情,但我想确定一下。

采纳答案by Haphazard

Static is static. They will reference the same object.

静态就是静态。他们将引用同一个对象。

回答by Bohemian

Static variables belong to the Classobject, 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".

静态变量属于Class对象,而不是实例。只有一个 Class 对象(对于那个类),所以只有一个静态变量的实例,所以“是的,他们都看到了相同的变量”。

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

如果变量是受保护的或公共的,则子类具有该变量的可见性。

回答by Prince John Wesley

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?

如果我现在启动 MyActivity1 并在“myStatic”中设置一个值。然后它退出,然后我启动 MyActivity2 - 我应该仍然拥有第一个活动设置的值吗?在上面的例子中,“if”语句是对还是错?

All subclass will share the same staticclass instance. so the ifstatement is true

所有子类将共享相同的static类实例。所以这个if陈述是真的