devxlogo

Method Storage

Method Storage

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.

See also  The Benefits of Patient Engagement Solutions for Healthcare Providers
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist