Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Java class, do we have separate copies of instance methods for each object of that class?

Tags:

java

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.

like image 606
Aditi Garg Avatar asked Dec 13 '22 21:12

Aditi Garg


2 Answers

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.

like image 106
Andy Turner Avatar answered Feb 23 '23 11:02

Andy Turner


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);
like image 39
daniu Avatar answered Feb 23 '23 10:02

daniu