A question in the object's size.

B

Bruce .J Sam

In order to show my question, I have written three simple class.
class A {
int id;
String name;
public void f() {}
public void g() {}
}
class B {
int id;
public void f() {}
}
class C extends B {
String name;
public void g() {}
}
Is it the size of the object of class C equal to the object of
class A, or bigger than it?
 
D

david

Bruce said:
In order to show my question, I have written three simple class.
class A {
int id;
String name;
public void f() {}
public void g() {}
}
class B {
int id;
public void f() {}
}
class C extends B {
String name;
public void g() {}
}

Is it the size of the object of class C equal to the object of
class A, or bigger than it?


Well, class A contains an int and a String member variable. Class C
contains an int and a String variable (one of which is inherited from
B), so it should be the same size as A.

This all assumes, of course, a very simple and straightforward Java
compilation model. At any rate, this is what you'd expect from what is
actually contained in the resulting compiled Java bytecode and symbol
table.

It also assumes that there are no alignment issues to deal with, and
that an int and a String variable are both one 32-bit "word" in size.
If a object reference is bigger (which could be the case on 64-bit
CPUs), then the order in which the base and derived members occur could
cause one class to be larger than the other because it contains padding
bytes to force proper alignment of the members. There is no general
rule about whether inherited members occur before or after derived
members in memory. In fact, there is no general rule about what order
the class members occur in at all; the JVM has a lot of
leeway in deciding how to arrange the member variables.

How the JVM actually chooses to lay out the object types in memory may
differ from this, for a variety of reasons. Generally, though, you're
safe in assuming that every object takes up at least one word, which is
its hidden class type pointer (similar to a C++ object's _vtbl
pointer), and possibly another word for a synchronization lock.
Implementing one or more interfaces may also complicate the memory
layout. In general, though, inheritance should not add any extra space
to objects other than the base class member variables.

-drt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top