This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes this operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this operator" Watch "this operator" New topic
Author

this operator

laks subramanian
Greenhorn

Joined: Feb 05, 2002
Posts: 17
folks
can anybody explain with an example why we use 'this'operator?
thanks
laks
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
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


SCJP Tipline, etc.
John Smiley
Author
Greenhorn

Joined: Mar 01, 2002
Posts: 17
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


<a href="http://www.johnsmiley.com" target="_blank" rel="nofollow">John Smiley</a><br />Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0072131896/ref=ase_electricporkchop" target="_blank" rel="nofollow">Learn to Program with Java</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: this operator