File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this operator" Watch "this operator" New topic

this operator

laks subramanian

Joined: Feb 05, 2002
Posts: 17
can anybody explain with an example why we use 'this'operator?
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,

SCJP Tipline, etc.
John Smiley

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="" target="_blank" rel="nofollow">John Smiley</a><br />Author of <a href="" target="_blank" rel="nofollow">Learn to Program with Java</a>
I agree. Here's the link:
subject: this operator
It's not a secret anymore!