Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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 Android Security Essentials Live Lessons this week in the Android 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
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3019

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: 1659

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: 273

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.

It is sorta covered in the JavaRanch Style Guide.
subject: Accessing Variables In a Class
Similar Threads
Question regarding encapsulation
What is "encapsulation"? How would I describe "encapsulation" in relation to a variab
Linking Tests and Requirements
What is Encapsulation
Encapsulation ?