• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this keyword

 
Jon Wilbanks
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
p.setFirstName("Joe");
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;
}
or--
public void setFirstName(String s)
{
this.fName = s;
}
Thanks for your help.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Marilyn de Queiroz
Sheriff
Posts: 9065
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Dave.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic