File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Accessing Variables In a Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing Variables In a Class" Watch "Accessing Variables In a Class" New topic

Accessing Variables In a Class

Erik Jordan

Joined: Jun 26, 2010
Posts: 1
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.

Devaka Cooray
ExamLab Creator

Joined: Jul 29, 2008
Posts: 3930

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.

Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1789

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.

When you do things right, people won't be sure you've done anything at all.
Michael Angstadt
Ranch Hand

Joined: Jun 17, 2009
Posts: 277

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.

I agree. Here's the link:
subject: Accessing Variables In a Class
It's not a secret anymore!