I would like to known if each instance of a class has its own copy of the methods in that class?
Lets say, I have following class MyClass
:
p
Each instance has its own set of instance variables. How would you detect whether every instance had a distinct "copy" of the methods? Wouldn't the difference be visible only by examining the state of the instance variables?
In fact, no, there is only one copy of the method, meaning the set of instructions executed when the method is invoked. But, when executing, an instance method can refer to the instance on which it's being invoked with the reserved identifier this
. The this
identifier refers to the current instance. If you don't qualify an instance variable (or method) with something else, this
is implied.
For example,
final class Example {
private boolean flag;
public void setFlag(boolean value) {
this.flag = value;
}
public void setAnotherFlag(Example friend) {
friend.flag = this.flag;
}
}
There's only one copy of the bytes that make up the VM instructions for the setFlag()
and setAnotherFlag()
methods. But when they are invoked, this
is set to the instance upon which the invocation occurred. Because this
is implied for an unqualified variable, you could delete all the references to this
in the example, and it would still function exactly the same.
However, if a variable is qualified, like friend.flag
above, the variables of another instance can be referenced. This is how you can get into trouble in a multi-threaded program. But, as long as an object doesn't "escape" from one thread to be visible to others, there's nothing to worry about.