简体   繁体   中英

Java Static Variables and inheritance and Memory

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?

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM