If the special variable this
refers to an Object in a variable/method that is being used. How does it know exactly which object it must refer to out of various objects in a program?
6 Answers
The mechanism is almost disappointingly simple.
Each instance method actually takes one more argument than you declare for it, and that extra argument is assigned to this
. Java syntax just thinly disguises this. When you write
list.get(0);
you have actually written
get(list, 0);
in a slightly modified way. The Java runtime resolves which get
method to call by inspecting the type of that first argument and locating the appropriate get
method in its class.

- 195,646
- 29
- 319
- 436
-
nice answer as usual @MarkoTopolnik – MaheshVarma Jan 29 '14 at 07:39
this
points to the current object instance that it is used in.
If you define a class A
with a method()
that contains a this
reference then you create two instances of the class
A a1 = new A();
A a2 = new A();
If you call a1.method()
then this
will refer to a1
, if you call a2.method()
then this
will refer to a2

- 8,163
- 2
- 41
- 53
From JAVA LANGUAGE SPECIFICATION
The keyword this may be used only in the body of an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.
The type of this is the class C within which the keyword this occurs.
At run time, the class of the actual object referred to may be the class C or any subclass of C.
The keyword this is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body (§8.8.7).
You can also refer to Oracle Tutorials

- 12,014
- 12
- 60
- 81
A a = new A();
a.doSomething(i) // is same as calling doSomething(a, i).
So, internally this
refers to "a". The first argument to the function will be the object (there will only be one method that will be used by all objects). So, argument o
will be the current object which has called this function.

- 8,163
- 2
- 41
- 53

- 35,966
- 12
- 68
- 104
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

- 4,395
- 10
- 43
- 74