• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this operator

 
laks subramanian
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
folks
can anybody explain with an example why we use 'this'operator?
thanks
laks
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The keyword "this" is a reference to the object we're currently in. Here's one example:

In the above example, the parameter s shadows the member variable s. Therefore, in order to access the member variable for assignment purposes, you need to use the keyword "this".
Take a look at this sections of the JLS: §15.8.3 this
and this recent thread: static, super, & this.
I hope that helps,
Corey
 
John Smiley
Author
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Laks
This can be a bear to explain (and Corey already did a good job of it).
Because I'm a teacher, I like to explain things using analogies.
A class is to an object like a blueprint of a car is to an actual car. When cars are produced from the blueprint design of an engineer, it's like an object being instantiated from a class that a Java designer has coded.
At the time the designer codes the class, he or she has no way of knowing the name (ie the object variable name) that the user of the class will use to refer to the particular instantiation of the object--that's why the designer of the class uses the keyword 'this'--to refer to the current instantiation of the object, no matter what it happens to be called.
Hope this helps.
John Smiley
If you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic