Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method sharing

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic