This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Method sharing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Method sharing" Watch "Method sharing" New topic

Method sharing

Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
Every Java object has its own copy of instance variables. Does each Java object also have a copy of the methods in the class?
Satish Kumar

Joined: Feb 18, 2005
Posts: 23
No, java & c++ objects dont create a copy of methods .

in above code a,b will have their own copies of x,y but a,b will share the meth() function.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
To be a bit more precise than "sharing a method" ... the JVM loads the bytecode for that method into memory once when the program first references the class. When you execute the method on instance 1 of the class or instance 2 of the class, the JVM steps through the very same instructions.

When you enter a method, the JVM makes new copies of the local variables, so they don't clobber each other. When you create a new instance, each instance gets its own copies of the member variables so they don't clobber each other.

This works out nicely. The JVM only loads the code once, saving some memory and time. It creates multiple copies of local and member variables to keep the object instances and threads separated. Does that make sense?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
It is sorta covered in the JavaRanch Style Guide.
subject: Method sharing
Similar Threads
java pass by copy, or pass by reference?
Session Objects
code not understood
Delegation event model.
Where exactly we make use of Clone objects in a real time?