Reputation: 39
After searching on the web I did not found yet a good and comprehensive answer about where exactly the instance variables are places inside Java Memory Model. For example we have this code (with shadowing declaration of variables):
class A {
int var = 1;
void m() {
System.out.println("\'m()\' is called from class A");
}
}
class B extends A {
int var = 5;
void m() {
System.out.println("\'m()\' is called from class B");
}
}
public class Class1 {
public static void main(String args[]) {
A aref = new B();
aref.m();
String s = (aref.var)==1?"A":"B";
System.out.println("\'var\' is called from class " + s);
}
}
Output of this code is:
'm()' is called from class B
'var' is called from class A
Now the question is not how inheritance works in Java but where in the Java Memory Model this instance variable resides? Please argument your answer.
Thanks
Upvotes: 3
Views: 595
Reputation: 14269
An Object is kept inside the heap, but as one block of memory equal to the size of all variables combined + some extra bytes to store the virtual method table (VMT) and the Object's prototype location (and possibly more depending on the JVM implementation).
So your example Object would look like this in (32-bit) memory (pointer values are just for presentation):
[0000] 0154 // pointer to prototype
[0004] 3625 // pointer to virtual method table
[0008] 0001 // int var
Now in your example above, no member is accessed, so all that the JVM does is to locate the VMT of that prototype, jump to the function address that is written down there and execute it.
If your var = 1
code actually makes it through the optimizer, the resulting assembly code would not know about this "var" thing, and instead work with direct memory access. Something like this:
set [4924 + 8], 1
Where 4924 is the instance's memory location and + 8 the offset to the variable var
. Keep in mind that this is the (made human readable) assembly and not the byte-code, so basically what is left once the JIT is done with it.
Since both your Objects are of the same size, it would even be possible to "upcast" A to B, the only reason it doesn't work, is because Java forbids such unsafe operations. In other less safe languages like C++, you could easily do that and probably get away with it.
Upvotes: 4
Reputation: 1451
Variables are different than methods when inheriting. Your method m() is overwritten in your B class when it extends A. However, B cannot override local variables of its parent class, as it does not have any jurisdiction over them.
Upvotes: 1