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?
Static variable's memory is allocated at the start of the program, in regular memory, instead of the stack (memory set aside specifically for the program). the advantage of this is that it makes your variable or procedure totally constant, and you can't accidentally change the value.
Static variables are inherited as long as they're are not hidden by another static variable with the same identifier.
Storage Area of Static Variable in Java Method area section was used to store static variables of the class, metadata of the class, etc. Whereas, non-static methods and variables were stored in the heap memory. After the java 8 version, static variables are stored in the heap memory.
When the program (executable or library) is loaded into memory, static variables are stored in the data segment of the program's address space (if initialized), or the BSS segment (if uninitialized), and are stored in corresponding sections of object files prior to loading.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With