wood burning stoves 2.0*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing Variables In a Class" Watch "Accessing Variables In a Class" New topic
Author

Accessing Variables In a Class

Erik Jordan
Greenhorn

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.

Thanks
E
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3268
    
  52

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: 1732
    
  12

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

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.


SCJP 6 || SCWCD 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing Variables In a Class