This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan 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 Android Security Essentials Live Lessons this week in the Android 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
Marshal

Joined: Mar 22, 2005
Posts: 41137
    
  45
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.


Ping & DNS - my free Android networking tools app
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why is assigning "size" that way considered WRONG?
 
Similar Threads
Comparator and Compatable Query
Array and Polymorphism questions.
array doubt
Assigning array references
transient