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
543 views
in Technique[技术] by (71.8m points)

memory allocation for a class in java?

class B inherits class A. Now when we create an object of type B, what is the memory allocated for B? Is it including A and B, or any other procedure for memory allocation?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you create the object B, let's say by calling the default constructor

B myObject = new B();

Then the JVM allocates an object with more or less:

  • Enough memory for every field explicitly declared in B (usually around 4-8 bytes per field, but it varies a lot from types and the host system)
  • Enough memory for every eventual field inherited by A and its ancestors
  • Enough memory to contain a reference to the dispatch vector (which should be around 4-8 bytes too)

The dispatch vector is used by the compiler to store the address of every method that can be invoked on the given object and it depends on the class of the object rather than the instance of the object itself (every object B has the same interface after all!)

So you do NOT need to allocate A, because there's no separate object A. You aren't instancing 2 separate objects. When you create B you are creating a "specialized" version of A.. which it can be viewed as A with something more. So only B needs to be allocated (but keep in mind that B also has everything its ancestors have)


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

...