Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

java - Inheritance and Object creation, Theoretically and in Real

Lets say I have a class A.java,

enter image description here

When I will execute a constructor method of A, it will create a memory space for xyz Object.

A xyz = new A();

The reference to memory may be something like,

[xyz] ---> '0x34524'

Thats basics of OOP. Simple enough!

Now,

What happens if a class is inheriting from different parent classes? How many object space will be created in memory?

Lets say we have,

enter image description here

and then we create an object of class D.java,

D omg = new D();

Here as we know that D's object will call construct of C.java and so on until A.java. Does this mean that in memory we are having 4 different memory reference, because we are instantiating all of the four objects (one directly and another 3 indirectly)?

[omg] ---> '0x34525'
[C]   ---> '0x34526'
[B]   ---> '0x34527'
[A]   ---> '0x34528'

Note :

  1. This isn't homework question, this is just a curiosity question.
  2. I am aware of the fact that if we have a instance variable inside an A.java then we will not create only object A but we will be creating other internal object whenever we hit new keyword.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...