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.
Are there three instances of the method foo in memory?
Does the JVM do some magic so that each object can use one method declaration in memory?
Is there a name for this situation so that I can see if other languages do it?
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?
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?
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.
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