Are methods copied when objects are created?

73 Views Asked by At

When a object is created, Java creates a copy of the attributes of the class, but, what happens, in memory, with the methods? Does Java create a copy of the code of these or creates only one copy of these for all the objects?

1

There are 1 best solutions below

9
On

They're not. Because Java is statically typed, an object looks something like this in the VM:

class_id,
field0,
field1,
...

The code of the method to call can then be associated with the class, not the object, so no duplication is needed. I'm guessing you're coming from a language like Python or Javascript where you can reassign methods on instances? In Java, you tend to do this with decorators, instead.