-4

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?

Sully
  • 14,672
  • 5
  • 54
  • 79
user3243076
  • 1
  • 1
  • 1

6 Answers6

3

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

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

Ross Drew
  • 8,163
  • 2
  • 41
  • 53
1

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

Prateek
  • 12,014
  • 12
  • 60
  • 81
1
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.

Ross Drew
  • 8,163
  • 2
  • 41
  • 53
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

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.

Oracle Java Tutorials

earthmover
  • 4,395
  • 10
  • 43
  • 74
0

this is a very important keyword that can differentiate between parent and child class objects. this refers to the present context in which object has too be referred to..!!

Ross Drew
  • 8,163
  • 2
  • 41
  • 53
Yasha
  • 161
  • 1
  • 4
  • 13