Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are instance methods stored [duplicate]

Tags:

java

memory

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 MyObjects 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.

like image 804
Samuel Avatar asked Dec 04 '11 17:12

Samuel


2 Answers

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.

like image 152
Óscar López Avatar answered Sep 21 '22 07:09

Óscar López


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.

like image 40
SJuan76 Avatar answered Sep 20 '22 07:09

SJuan76