permaculture playing cards*
The moose likes Beginning Java and the fly likes 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" is optional ?" Watch ""this" is optional ?" New topic
Author

"this" is optional ?

mike zhang
Ranch Hand

Joined: Feb 26, 2002
Posts: 59
In a constructor, when I do
"this.name = input_name;"
it is equivalent to
" name = input_name;"
as long as I have
"private String name;" declared in the class. Right ?
MIke
zoe goddard
Ranch Hand

Joined: Dec 12, 2000
Posts: 74
Yes, it should be as long as you don't have a local variable called name in the constructor.
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Originally posted by zoe goddard:
Yes, it should be as long as you don't have a local variable called name in the constructor.

Right... normally you use the keyword 'this' to differentiate between a local variable and an class variable... like this:
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Originally posted by Jessica Sant:
Right... normally you use the keyword 'this' to differentiate between a local variable and an class variable... like this:

Yeah, thats the way I always do it, but be aware that there are some stupid things you can do wrong that make it very difficult to debug.
If you accidentally spell the parameter name wrong...

Now the variables in this.value=value both refer to the same variable. It won't fail, but nothing will happen and you'll get frustrated and then annoyed. Possibly followed by anger and violence.
Didn't stop me from doing it though.
 
 
subject: "this" is optional ?
 
Similar Threads
Session expiration in struts using nested tags
Cup Symbol.
Help Window
JUNIT to test EJB
getElementByID not working in Firefox but works in IE?