*
The moose likes OO, Patterns, UML and Refactoring and the fly likes what are setters and getters for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "what are setters and getters for" Watch "what are setters and getters for" New topic
Author

what are setters and getters for

Ronwaldo Cruz
Ranch Hand

Joined: Oct 17, 2006
Posts: 69
Setters and getters are used to provide access to a private variable. Could someone please explain why not just access the variable directly like sampleObject.attribute = "Value" or String attributeValue = sampleObject.attribute? What are the pitfalls of this direct access approach
Daniel Dalton
Ranch Hand

Joined: Mar 20, 2005
Posts: 146
A couple of things (at least)

1) encapsulation. The thing you are setting/getting may be complex - eg. You might create a getter that formats a Date object into a String for example.

2) By following a convention they enable tools to use reflection to manipulate them without having to know field names before hand. BeanUtils gives some examples.
Ananth Chellathurai
Ranch Hand

Joined: Nov 21, 2007
Posts: 349

Hey Cruz,

More on getter setters could help you.

Ananth Chellathurai


Ananth Chellathurai [Walk on software]
Ronwaldo Cruz
Ranch Hand

Joined: Oct 17, 2006
Posts: 69
Hi Ananth,

I've actually read the article but it's anti-"setter getter". What I'm trying to do is to solicit pro-"setter getter" opinions.

Hi Daniel,

Example #1: These cases are in my opinion quite rare and in any case does not necessitate having setters and getters for all the other fields

Example #2: I think these tools built on the fact that there are setters and getters so they adjusted to the situation they found. If this is not the case, I do believe they still would have found to work their way around
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: what are setters and getters for
 
Similar Threads
Private variable problem
Sample question
How to know a variable is accessed?
Data Transfer Object query
hbm2java - private members ?