Memory Allocation for objects in java

1.4k views Asked by At

I am a beginner in Java and I had completed C++. In C++,the memory allocation for member functions is done at the time they are declared as a part of a class and not when the objects are created,when the objects are created,then only the memory allocation for the instance variables is done,that is for every object memory allocation for instance variable is done seperately and the member functions are shared commonly by all the objects. In case of instance variables,I know the same case happens in java,but what happens in case of member functions?

In C++; For e.g. if we have 2 instance variables a and b,and we had created 3 objects x,y,z and let us say we have a member function getData(), then all the 3 objects have a seperate copy of the two instance variables a and b,but share a common copy of getData().

For instance variables,same is the case in java,but what for member functions?

2

There are 2 answers

1
Sam Estep On

In Java, member functions are loaded on-demand by the classloader. Since the entire Java standard library is available alongside any Java program, and the program itself may contain any number of classes, this is necessary in order to keep program start times in the range of sanity.

So any time the program needs a class in any way (e.g. to access a static variable or method, or to create an instance of an object) that isn't already loaded, the Java classloader loads that class, which includes the class's member functions. Then, once that class is loaded, it doesn't need to be loaded again if it's needed in the future, because similarly to what you noted in your question, only one copy of the class bytecode is necessary at any given time.

To avoid accumulating more and more loaded classes as the program runs, Java uses garbage collection to unload classes that it knows it can safely unload, similarly to how it uses garbage collection for program data. Those classes can of course be reloaded later if they are needed again. There are, of course, situations in which unloading a class wouldn't work due to the risk that reloading it would cause static variables/code to be reinitialized/run.

This ability to unload and reload classes can also be put to use in debugging: IntelliJ IDEA has a HotSwap feature that allows you to edit and recompile a class while the program is running, unload that class, then reload the new bytecode so you can quickly test ideas. (Wow, I just realized that totally sounded like an advertisement. I'm not affiliated with JetBrains, in case you're wondering.)

0
Jesper On

In Java, the bytecode for the methods exists only once for a class; no copy of the method's bytecode is made for every object. That would be unnecessary and wasteful; the bytecode does not change while the program runs.

So it works the same as what you say for C++:

... the member functions are shared commonly by all the objects.