| 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
Saloon Keeper
Joined: Jul 29, 2008
Posts: 2694
|
|
|
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 (Download) - the free mock exam kit for SCJP / OCPJP
Home Page -- Twitter Profile -- JavaRanch FAQ -- How to Ask a Question
|
 |
Janeice DelVecchio
Saloon Keeper
Joined: Sep 14, 2009
Posts: 1612
|
|
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: 272
|
|
|
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
|
 |
 |
|
|
subject: Accessing Variables In a Class
|
|
|