Java Static Variables and inheritance and Memory

那年仲夏 提交于 2020-01-23 06:31:45

问题


I know that if I have multiple instance of the same class all of them are gonna share the same class variables, so the static properties of the class will use a fixed amount of memory no matter how many instance of the class I have.

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

And if not, what is the best practice/pattern to make sure they share the same class variables?


回答1:


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

Yes They will share the same class variables throughout the current running Application in single Classloader.
For example consider the code given below, this will give you fair idea of the sharing of class variable by each of its subclasses..

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



回答2:


All the instances of that class or sub-class share the same static fields for a given class loader.

Note: if you load the same class more than once in multiple class loaders, each class loader has it's own copy of static fields.




回答3:


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.



来源:https://stackoverflow.com/questions/15596955/java-static-variables-and-inheritance-and-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!