File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use getters and setters

 
Lloyd Blake
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should you always use getters and setters in your code or are they only for certain situations?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are a way to encapsulate your instance variables, hence the answer is always.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Sebastian said,it is not good Idea to expose a class Instance variable to other class(which is in different package) directly . additionaly , using setter and getter method you can apply some logic before you set the value to a reference/variable and also you can apply synchronization stuff
example,



hth
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To augment to that, even if your setter/getter does not implement any logic and plainly sets/gets the values, you reserve the possibility to do so later. If you expose instance variables to the outside world, you are forced to do so forever and are hardly able to change your implementation later.

Also, there is no way to control the state of your object. Imagine a public instance variable called weight which takes an int value. If it public you could assign -50 which is an illegal value and puts your object into an inconsistent state.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic