I have a memory question regarding creating objects in java-language.
When one creates an object in java a certain memory-space is occupied on the heap - correct? But what is part of this memory? Is it membervariables or both membervariables and methods? Could it be so that several object that refers to the same class share something?
Let say I have the following class
class MyClass {
//Membervariables
protected int age;
protected long dateOfBirth;
/**
* Constructor
* @param age
*/
public MyClass(int age) {
this.age = age;
}
/**
*
* @param dateOfBirth
*/
protected void setDob(long dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
/**
*
* @return
*/
protected int getAge() {
return this.age;
}
/**
*
* @return
*/
protected long getDob() {
return this.dateOfBirth;
}
}
So in this class I have the following: - Two membervariables - one int and one long
one constructor
one mutator-method
one accessor-method.
In the main-method I create two-instances (objects) of this class:
MyClass myClass1 = new MyClass(10);
MyClass myClass2 = new MyClass(11);
So my question is:
1) How could this be depicted in the computers memory?
2) Could the same "architecture" of how things are stored in memory concerning objects be applied to c++ as well?
Thanks in advance!!!
An object consists of a pointer to the internal version of the class, an area used for synchronized locking, an area of GC flags, and the instance fields defined in the class. (Note that an object reference field is only a pointer -- the referenced object is allocated separately.)
Methods are located by following the class pointer to the class and indexing a method table in the internal class object.
Your object above, in a 64-bit JVM, would be roughly:
36 bytes total. (Less, of course, in a 32-bit JVM.) The 36 bytes would likely be rounded up to 48 bytes to put it on a 16-byte boundary, or at least 40 to put it on an 8-byte boundary.
(This is one possible implementation. There are tricks that can be used to reduce/combine the space for the lock and GC fields, eg. But the basic principles apply.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With