Inheritance and Object creation, Theoretically and in Real

前端 未结 3 1072
庸人自扰
庸人自扰 2020-12-16 06:44

Lets say I have a class A.java,

\"enter

When I will execute a con

相关标签:
3条回答
  • 2020-12-16 07:14

    First, a tid bit... calling the constructor of an object does not allocate it. In bytecode, the initialization new Object() is expressed as something to the effect of...

    new java/lang/Object
    invokespecial java/lang/Object <init>()V
    

    The new instruction takes care of allocating the space and acquiring a reference to the yet uninitialized object, while the invokespecial handles calling the constructor itself (which is internally compiled to a void method named <init>, hence the descriptor <init>()V).

    Moving on, internals of object allocation and representation on the heap are entirely JVM specific. However, as far as I know, there is only one allocated object per allocated object, no matter its number of super classes. The object itself in memory has space for the instance fields of both its own class and its super classes. It must also have space for a virtual method table, in order to do virtual dispatch when performing virtual method calls (e.g. via invokevirtual) for the object.

    Internally, the Oracle HotSpot JVM manages things called oops, or ordinary object pointers. You can read more about the HotSpot memory layout here. Feel free to browse the HotSpot source repository.

    0 讨论(0)
  • 2020-12-16 07:21

    I have not read this anywhere but its my experience. When you call new D(), the constructor chain begins, it first creates an java.lang.Object and then extends it to an A, I mean after creating the Object (which is root of all objects), A is initialized on it, by adding memory for A's members, including fields and methods (which are a pointer to some code!). And then it extends to B and so on.

    In the process of extension if a method is overriden, the method pointer in the object will point to new code.

    It will be only one reference to D.

    0 讨论(0)
  • 2020-12-16 07:30

    JVM allocates memory for only one object (here D)

    1. memory allocation and initialization happens bottom(here D) to top(Object)
    2. initialization/calling constructors happens Top(Object) to Bottom(here D)

    reference :

    http://www.artima.com/designtechniques/initialization.html

    0 讨论(0)
提交回复
热议问题