-5

It is true that each object has its own copy of instance variables. But is it true that like static members, there is only one copy of instance methods? If yes, then where it resides in memory?

  • 1
    Possible duplicate of [Java memory model for static methods](https://stackoverflow.com/questions/28100825/java-memory-model-for-static-methods) – Progman Sep 26 '17 at 20:40
  • each object has its own copy of instance variables and instance methods. static variables and static members exist as one per class – SkrewEverything Sep 26 '17 at 20:40
  • Each object has its own copy of the instance variables, but not of the static variables, or any of the methods. There is only one copy of the instance methods, but a reference to the owning object is put on the stack when an instance method is called, so that the runtime can identify which instance the method was called on. – Dawood ibn Kareem Sep 26 '17 at 20:42

3 Answers3

1

There only needs to be one copy of instance methods in memory. When an instance method is called there will be a "this" variable implicitly included in the stack. The "this" variable allows the instance method to access the instance variables for the object instance that called it.

Classes, including their methods, would typically end up in the long lived heap as it is uncommon for them to be garbage collected.

Jason Mathison
  • 1,181
  • 1
  • 10
  • 18
0

But is it true that like static members, there is only one copy of instance methods?

Yes, regardless of the number of instances and whether a method is static or not, there is only one copy of it for all the objects.

If yes, then where it resides in memory?

heap.

VHS
  • 9,534
  • 3
  • 19
  • 43
0

Yes. Logically, a method in every instance of one class, shares one algorithm. Memory behaves in a similar way. Each object calls one method algorithm and required values are pushed to the stack temporary during the method call.

Method is a set of instructions to follow, not a data structure. It should not specifically allocate memory.

Method call instructions are stored in RAM separately, as same as other application instructions. This is not a part of Java memory allocation process.

Shevon Silva
  • 139
  • 1
  • 3