Possible Duplicate:
Java/C# method representation in memory
I was wondering if i have an object in java, how are it's instance methods stored? Does an object have a pointer to it's instance methods?
Example:
public class MyObject {
private int x;
private int y;
[..]
}
If i plan keeping a lot (A big tree of objects for example) of these MyObject
s in memory, will it make a significant difference in memory terms if apart from a getter for x and for y i define an instance method calculating the sum?
I'm trying to sort out wether i should add more instance methods or doing the calculations in another class using the getters and setters.
The instance methods of an object are stored in its class object (only one copy should exist), they are not "copied" with each new instance, instead, under the hood each instance holds a reference to the method implementation residing in the class object.
For a technical explanation, take a look at this chapter from the book "Inside the Java Virtual Machine", in particular the "Object Representation" section; it details how each instance of an object references its methods in the corresponding class. Notice that the implementation details for this are not present in the JVM specification, and they're left open to the implementors - the linked document presents several strategies.
The object needs memory for its attributes (NOTE: for object, the attribute stored is a pointer to the real object, which lies elsewhere in memory). No additional memory is needed for methods (code) as they are stored with the class.
IE:
public class MyClass1 {
private int myNumber;
}
and
public class MyClass2 {
private int myNumber;
public int MyMethod1() {
}
public int MyMethod2() {
}
public int MyMethod3() {
}
....
public int MyMethod1000() {
}
}
use the same memory per instance.
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