• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing Variables In a Class

 
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
ExamLab Creator
Marshal
Pie
Posts: 4253
227
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
Saloon Keeper
Posts: 1807
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: 277
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