wood burning stoves
The moose likes Beginning Java and the fly likes this keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "this keyword" Watch "this keyword" New topic

this keyword

Jon Wilbanks

Joined: May 11, 2001
Posts: 3
What is the general rule about when you should use the 'this' keyword? If I understand what I've read about it, when you create a object like:
Person p = new Person();
and then you call a method of the Person class like:
then a 'this' pointer is sent along with the method call.
So the question is should the method be:
public void setFirstName(String s)
fName = s;
public void setFirstName(String s)
this.fName = s;
Thanks for your help.
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
If you declared the variable outside the method as an instance variable you can just use fName = s;
Where the "this" comes in handy is when you try to tell the difference between a local variable and an instance variable that have the same name.
String fName;
public void setFirstName(String fName)
this.fName = fName;
Here you are telling the JVM to set the instance variable fName to the same value as the local variable fName.
Also "this" is used alot in constructors to call a different version of the overloaded constructor. For instance if you have a default constructor that calls a more complicated constructor using a bunch of default values for variables since the user didn't provide any input parameters.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9059
In this example the methods are equivalent. The "this" is implicit in the first case and explicit in the second.

[This message has been edited by Marilyn deQueiroz (edited May 15, 2001).]

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

I alway use 'this' for getters/setters as in

etc etc, but the thing to be really careful of is that if you spell the method parameter incorrectly then both 'name' and 'this.name' will refer to the same variable
I agree. Here's the link: http://aspose.com/file-tools
subject: this keyword
It's not a secret anymore!