Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes When to use getters and setters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to use getters and setters" Watch "When to use getters and setters" New topic

When to use getters and setters

Lloyd Blake

Joined: Dec 24, 2008
Posts: 6
Should you always use getters and setters in your code or are they only for certain situations?
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
They are a way to encapsulate your instance variables, hence the answer is always.

JDBCSupport - An easy to use, light-weight JDBC framework -
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

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

Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: When to use getters and setters
It's not a secret anymore!