This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Why is assigning Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why is assigning "size" that way considered WRONG?" Watch "Why is assigning "size" that way considered WRONG?" New topic
Author

Why is assigning "size" that way considered WRONG?

Abder-Rahman Ali
Ranch Hand

Joined: May 22, 2008
Posts: 138
Why is assigning "size" that way considered WRONG?


Ulf Dittmer
Rancher

Joined: Mar 22, 2005
Posts: 42958
    
  73
It is not "considered" wrong, it is incorrect. In the body of the setSize method, "size" refers to the parameter, not to the instance variable. So what that assignment does is assign the parameter to itself - in other words, it does nothing. Especially the value of the instance variable of the same name is not changed.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Because it won't do what you intend it to: you're assigning a variable to itself, not to the class member.
Abder-Rahman Ali
Ranch Hand

Joined: May 22, 2008
Posts: 138
Thanks.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Try changing your setSize() method to this:



Using the 'this' keyword tells the compiler you want to set the instance variable to the value of the parameter.

John.
Abder-Rahman Ali
Ranch Hand

Joined: May 22, 2008
Posts: 138
Thank you very much.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why is assigning "size" that way considered WRONG?
 
It's not a secret anymore!