This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing Variables In a Class  RSS feed

 
Erik Jordan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When accessing Variables in the same class is it best practise to use encapsulation (Getters and Setters) or direct access via the dot operator?

I know its good practise to use encapsulation when accessing Variables in other classes.

Thanks
E
 
Devaka Cooray
Marshal
Posts: 5511
687
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on the design of the class. In most cases, unless on a specific requirement, you may directly access the private variables within the same class.
 
Janeice DelVecchio
Bartender
Posts: 1812
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

Devaka makes a good point, just remember it is a good practice to make your member variables private. So if you will need them from a different class. you'll need a getter.
 
Michael Angstadt
Ranch Hand
Posts: 278
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on what your getters and setters are doing. If they are just getting and setting the field, then you might as well access the fields directly. But if they do something that would require you do duplicate code, then you should call the method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!