Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 591
alessiop86 Avatar asked Mar 24 '13 09:03

alessiop86


People also ask

Do static variables take more memory?

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.

Are static variables inherited Java?

Static variables are inherited as long as they're are not hidden by another static variable with the same identifier.

How are static variables stored in memory Java?

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.

How are static variables stored in 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.


1 Answers

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
    }
}
like image 183
Vishal K Avatar answered Sep 28 '22 13:09

Vishal K