• Post Reply Bookmark Topic Watch Topic
  • New Topic

get and set  RSS feed

 
David Starr
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) Are both get and set established methods (from the API) or is it only Java best practice convention?
2) In other words, does Java recognize both of these two examples as using the practiced use of getters and setters?
3) If it is an established method in the Java API, where is it?
A)

B)

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The get/set method naming practice is primarily convention However, it's also used for JavaBeans introspection. Using java.beans.Introspector and java.beans.SimpleBeanInfo, the bean properties will be default be determined by examining the get/set methods. Presumably this default behavior is based on the convention. It can be changed, though. I think its done by providing your own BeanInfo class, although this would be a fairly uncommon thing to do.

Note that it is NOT best practice to just blindly throw getters and setters on every member variable. In general, an object's implementation of its state should be private, and that state should be reflected only by behavior that makes sense for what that object's role is.

For some members of some classes, it will make sense to provide a direct getter and/or setter, but in general, you should NOT do so unless and until you find a valid reason to do so. And there are families of classes--such as DTOs whose job is just to contain data, but who don't have any real behavior--where it's appropriate to provide get/set for everything.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!