This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"this" is optional ?

 
mike zhang
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it should be as long as you don't have a local variable called name in the constructor.
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic