If non-static functions are copied into the heap for each object that has that method, then why aren’t all methods in Java static by default? Why waste all of that heap memory this way?
A diagramic explanation would be more helpful for me to understand this.
Typically, Java methods are not implemented by copying the method onto the heap once per object. Instead, methods are typically implemented using something called a virtual function table (or “vtable”). The idea is that there is exactly one copy of each method, whether it’s a static or nonstatic method, and pointers to these methods are laid out into a table. Each object in the heap then stores a pointer to the vtable for its object type. This means that the size of any heap object does not depend on the number of methods the object has. In fact, an object with 100 methods would be the same size an object with 1 method (assuming they have the same fields). Each just stores a pointer to the vtable for its object type, of which there’s only one copy.
This optimization was originally used in C++ to support fast virtual functions and has since been used in many other object-oriented languages. It allows objects to be small, yet support dynamic dispatch.
In other words, methods don’t need to be
staticby default because they don’t contribute to the size of the objects in the heap. Creating an object doesn’t take longer for objects with more functions, or does it use more heap space.Here’s one possible diagram for the layout of some objects (apologies for ASCII art!). Suppose that we have two classes, A and B. Then in memory, objects of those types might look like this:
Notice how both objects of type A share the same vtable, and how objects of types A and B only use the same amount of space for their vtable pointer, even if they have different numbers of methods.