Kevin Park Kevin Park - 11 months ago 35
Java Question

How is the 'this' variable in Java actually set to the current object?


class TestParent{
public int i = 100;
public void printName(){
System.err.println(this); //{TestChild@428} according to the Debugger.
System.err.println(this.i); //this.i is 100.

class TestChild extends TestParent{
public int i = 200;

public class ThisTest {
public static void main(String[] args) {
new TestChild().printName();

I know that similar questions have been asked, but I couldn't get a firm understanding of the 'this' variable in Java.

Let me try to explain how I understand the result of the above image.

  1. Since it's a
    new TestChild()
    object that's calling the
    method, the
    variable in line 6 is set to a
    object - {TestChild@428} according to the Debugger.

  2. However, since Java doesn't have a virtual field - I'm not completely sure what this means, but I conceptually understand it as being the opposite of Java methods, which support Polymorphism -
    is set to 100 of
    at compile time.

  3. So no matter what
    in a
    method will always be the
    variable in the

I'm not sure that my understanding is correct so please correct me if I'm wrong.

And also, my main question is,

How is the
variable set to the current object that's calling the method? How is it actually implemented?

Answer Source

In essence, there is no difference between


as both are "implemented" the same way. What happens is that in reality, this happens:


In other words: whenever you use some object reference to call a method ... in the end there isn't a call on some object. Because deep down in assembler and machine code, something like "a call on something" doesn't exist.

What really happens is a call to a function; and the first (implicit/invisible on the source code level) parameter is that object.

BTW: you can actually write that down in Java like:

class Bar {
   void foo(Bar this) { ... }

and later use

new Bar().foo();

And for this.fieldA, in the end: you have a reference to some location in memory; and a table that tells you on which "offset" you will find fieldA.

Edit - just for the record. If you are interested in more details about foo(Bar this) - you can turn to this question; giving the details in the Java spec behind it!