我知道如果我有同一个类的多个实例,它们都会共享相同的类变量,所以无论我有多少类的实例,类的静态属性都将使用固定数量的内存.
我的问题是: 如果我有几个子类从它们的父类(super class)继承一些静态字段,它们会共享类变量吗?
如果不是,确保它们共享相同的类变量的最佳实践/模式是什么?
最佳答案
If I have a couple subclasses inheriting some static field from their superclass, will they share the class variables or not?
是的,它们将在单个类加载器中在当前运行的应用程序中共享相同的类变量。
例如考虑下面给出的代码,这将使您清楚地了解每个子类共享类变量。 .
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
}
}
关于Java 静态变量和继承与内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596955/