• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

"this" is optional ?

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, it should be as long as you don't have a local variable called name in the constructor.
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic