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
Joined: Sep 29, 2000
Posts: 8521
posted
0
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
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
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).]
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
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.