Home Ask Login Register

Developers Planet

Your answer is one click away!

angel February 2016

keyword 'this' shown as a variable name

I am a beginner in java coding and I am having a hard time understanding the below scenario. Below is the screen shot of eclipse, while I was trying to debug my program. I could not understand why the variables section in the top right corner shows this as a variable name and the value of this as Test(class name). I always thought this is a pointer and not a variable. And moreover, the object for class test is not yet created. So, what is it referencing to? if you see the screenshot this is not used in the program. Still while debugging this is shown as a variable name

Eclipse screenshot

can anyone help me with this ?


Jon Skeet February 2016

From section 15.8.3 of the JLS:

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method or default method was invoked (ยง15.12), or to the object being constructed.

So you can sort of regard it as a read-only variable, basically. You can do the same thing with it that you can do as most other variables.

In your screen-shot, your execution is at the start of a constructor - so this refers to the object currently being initialized.

TheLostMind February 2016

this represents the current object in the current context. In any given instance context (method), this represents the object on which this method was called.

Note that for any call of an instance method the object (this) is implicitly passed. So, you see the instance of this in the variable section.

this is not exactly a reference (technically it actually points to the current object).

Frank February 2016

A pointer is a variable. It is a variable that contains a memory address for the object being referenced.

In you debug window, note the "(ID=18)". This is an internal ID for the individual object. So your object has been instantiated, and the this keyword is currently referring to the instance of that object with ID 18.

If your debugger is on this file, then the object has been allocated. If I remember my Eclipse debugging correctly, it looks like the constructor is being called. This means that all static items have been evaluated, and your object is ready to execute it's constructor - meaning it's already been allocated.

Post Status

Asked in February 2016
Viewed 3,068 times
Voted 6
Answered 3 times


Leave an answer

Quote of the day: live life