6

我知道如果我有同一个类的多个实例,它们都将共享相同的类变量,所以无论我有多少类实例,类的静态属性都将使用固定数量的内存。

我的问题是: 如果我有几个子类从它们的超类继承一些静态字段,它们会共享类变量吗?

如果没有,确保它们共享相同的类变量的最佳实践/模式是什么?

4

3 回答 3

17

如果我有几个子类从它们的超类继承一些静态字段,它们会共享类变量吗?

是的,它们将在单个类加载器中在当前运行的应用程序中共享相同的类变量。
例如,考虑下面给出的代码,这将使您清楚地了解每个子类共享类变量。

class Super 
{
    static int i = 90;
    public static void setI(int in)
    {
        i = in;
    }
    public static int getI()
    {
        return i;
    }
}
class Child1 extends Super{}
class Child2 extends Super{}
public class ChildTest
{
    public static void main(String st[])
    {
        System.out.println(Child1.getI());
        System.out.println(Child2.getI());
        Super.setI(189);//value of i is changed in super class
        System.out.println(Child1.getI());//same change is reflected for Child1 i.e 189
        System.out.println(Child2.getI());//same change is reflected for Child2 i.e 189
    }
}
于 2013-03-24T09:38:58.307 回答
6

对于给定的类加载器,该类或子类的所有实例共享相同的静态字段。

注意:如果您在多个类加载器中多次加载同一个类,则每个类加载器都有自己的静态字段副本。

于 2013-03-24T09:40:49.917 回答
0

Yes all the class hierarchy(same class and all child classes instances) share the same static variable. As the JAVA doesn't support the global variable but you are able to use the static variable as a Global variable without violation of OOP concepts.

If you changed the value of static variable from one of the class, the same changed value replicated to all the classes that uses this variable.

于 2013-03-24T09:56:50.440 回答