Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do java objects share method location in memory?

Consider this class:

public class Test {
    private int bar = 5;

    public void foo () {
        System.out.println("hi");
    }
}

Now imagine we have the following section of code executing:

Test obj1 = new Test();
Test obj2 = new Test();
Test obj3 = new Test();

All three objects exist in the same scope. Because bar is not static, there will be three separate instances of bar in memory.

  1. Are there three instances of the method foo in memory?

  2. Does the JVM do some magic so that each object can use one method declaration in memory?

  3. Is there a name for this situation so that I can see if other languages do it?

like image 376
user13482 Avatar asked Mar 20 '14 00:03

user13482


3 Answers

Methods are referenced by indices, there are no instances of methods, i.e. they don't take up additional memory.

The Java instruction set responsible for handling a method based on a class is invokevirtual:

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.invokevirtual

Here is a more detailed look of what happens under the hood (explained far better then I could):

http://zeroturnaround.com/rebellabs/java-bytecode-fundamentals-using-objects-and-calling-methods/


Other references

How the hava virtual machine handles method invocation and return

Here is a similar SO question: How much memory is used for function references in a Java object?

like image 159
ılǝ Avatar answered Oct 24 '22 19:10

ılǝ


Are there three instances of the method foo in memory?

No.

Does the JVM do some magic so that each object can use one method declaration in memory?

No.

Is there a name for this situation so that I can see if other languages do it?

What makes you think there are any other languages that do it? The real question here is why do you think methods would be instantiated per instance? What would be the point?

like image 22
user207421 Avatar answered Oct 24 '22 18:10

user207421


To be clearer, there is absolutely no need for different objects to have different code for their methods. Assuming you have 3 instances of Test, you need three versions of the 'bar' member because they can have different values. However all of the three 'foo' methods do exactly the same thing. The bits that represent the code are absolutely identical. Having three (identical) versions would be completely pointless.

All other computer languages do this too. In fact you will find that on a computer, if you execute (say) a text editor on three documents at once, there will be three areas of data representing the three documents, but only one place in memory where the actual code of the application is stored. The three 'instances' share it.

like image 40
DJClayworth Avatar answered Oct 24 '22 18:10

DJClayworth