Java static variables and inheritance and memory

I know that if I have several instances of the same class, they are all going to use the same class variables, so the static properties of the class will use a fixed amount of memory no matter how many instances of the class I have.

My question is: If I have several subclasses inheriting some kind of static field from their superclass, will they separate the class variables or not?

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

+5
source share
3 answers

, - , ?

Loadload. , , .

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

.

. , .

+6

Yes, all class hierarchies (the same classes and all child classes) use the same static variable. Since JAVA does not support a global variable, but you can use a static variable as a global variable without violating OOP concepts.

If you changed the value of a static variable from one of the classes, then the same changed value was replicated to all classes using this variable.

0
source

All Articles