If not, how exactly at run time, do the instance methods use the instance variables of the same object?
For example I have a class A, having instance variable aVariable
and non static method aMethod()
. Now I have an object of class A, let's name it aObject. aMethod
makes use of aVariable
. When I invoke this method, how does it know, in memory, which aVariable
to use, and where it is stored? Do we pass all the object information to the method?
Please help me with this.
Refer to the JVM Spec, Sec 3.7:
int add12and13() { return addTwo(12, 13); }
This compiles to:
Method int add12and13() 0 aload_0 // Push local variable 0 (this) 1 bipush 12 // Push int constant 12 3 bipush 13 // Push int constant 13 5 invokevirtual #4 // Method Example.addtwo(II)I 8 ireturn // Return int on top of operand stack; // it is the int result of addTwo()
The invocation is set up by first pushing a reference to the current instance, this, on to the operand stack. The method invocation's arguments, int values 12 and 13, are then pushed.
So, the this
reference (or any other value of the receiver parameter) is just pushed onto the stack as another argument. As such, separate copies of the method are not required per instance.
No, we do not have separate copies for instance methods.
The way this is done is by passing an implied reference to this
:
For a method
public void doSomething(Object param);
, calling
this.doSomething(myParameter);
is resolved to
doSomething(this, myParameter);
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