Java instantiation

>When an object is instantiated in Java, what really enters memory?

I understand the usual Abstract explanation for the correct use of these things, but how does the JVM really do it

Solution

When an object is instantiated, only non - static data is actually "created" and a reference to the object type that created it

No method is copied

The "reference" of the class that created it is actually a pointer dispatch table There is a pointer to each method available for this class The pointer always points to the "correct" of the method (usually the lowest / most specific in the object tree)

In this way, if you have a top-level method that calls another method, but the other method has been overridden, the overridden method will be called because this is the pointer in the table Because of this mechanism, it should not take more time to call the override method than the top-level method

Pointer table member variables are "instances" of classes

The problem of mutability is related to a completely different mechanism "namespace" Variables are not "subclassed" (they do not enter the dispatch table), but public or protected variables can be hidden by local variables This is done by the compiler at compile time, independent of runtime object instances The compiler determines what you really want and references it into your code

Scoping rules usually favor "nearest" variables Anything away from the same name will be ignored (shadow) in favor of a closer definition

If you are interested, learn more about memory allocation: all "objects" are allocated in the "heap" (actually, it is more pleasant and beautiful than the real heap, but the same concept) variables are always pointers – Java will never copy an object, you will always copy a pointer to that object The variable pointer assignment of method parameters and local variables is completed on the stack, but even if variables (pointers) are created on the stack, they still never allocate the object they point to on the stack

I'd love to write an example, but it's too long If you want me to output several classes with extended relationships, and how their methods and data affect code generation, I can... Just ask

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>