Java静态变量和继承和内存

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

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

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

解决方法

If I have a couple subclasses inheriting some static field from their
superclass,will they share the class variables or not?

是的,它们将在单个Classloader中在当前运行的Application中共享相同的类变量.例如,考虑下面给出的代码,这将为您提供每个子类共享类变量的公平概念.

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
    }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...