This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript 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.
 
Don't get me started about those stupid light bulbs.
 
subject: "this" is optional ?