Question:
Does each instance of a class have its own copies of instance methodsin the same way it has its own copies of instance variables?
Answer:
Every time you instantiate a class, new memory is allocated to storethe object. Part of this storage includes space for copies of itsmember variables. Rather than create a new copy of each methodinto a class instance, which would be rather expensive, a virtuallookup table mapping methods to code blocks is allocated.
You canthink of class methods as functions that take an invisible argumentthat references the invoking instance, i.e., the this reference.That makes it possible to store methods independent of instantiatedclasses. When a class instance invokes a method, a lookup isperformed in its virtual function table to find the proper codeblock to execute.
Therefore, all class intances share the same code,but have their own data. Novel runtime optimization techniques havebeen applied to improve the performance of virtual function lookups inJava so that you only pay a lookup penalty the first time you invokea method.