Let's say we have a class
public class ThisTest {
String username;
ThisTest(String s) {
this.username = s;
}
public void sayHello() {
System.out.println("Hello " + this.username);
}
public static void main(String args[]) {
ThisTest a = new ThisTest("Jack");
ThisTest b = new ThisTest("George");
a.sayHello();
b.sayHello();
}
}
Output (as expected):
Hello Jack
Hello George
My question is: inside the sayHello method, how does the runtime determine which object instance on the heap "this" refers to.
on compilation, is the method call passed a hidden reference to the calling object (a or b) which is then accessed using the "this" keyword ? - This is what C++ does.
or, is "this" a hidden instance variable of the object on the heap created when the object is constructed?
or, is there some other mechanism by which the sayHello method knows which object "this" refers to?
Essentially, how is "this" implemented at the compiler level in Java.