File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Accessing variables from other classes 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 from other classes" Watch "Accessing variables from other classes" New topic
Author

Accessing variables from other classes

Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
What's the difference if I create a get method in a class for a variable versus giving the variable no access modifier(so it can be accessed within that package) and accessing it by
ClassName.variable
What is the proper way, and does one or the other leave the variable in memory longer?
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Jennifer,
There are no differences in memory. However, using get/set methods to give access to instance variables is the proper way to do things. The official term is "encapsulation" and it's your first step toward creating a good design for your components. The idea is that when you reveal your variables directly, other components will use them. And then, what happens when you need to change those variables somehow? The answer: bad things happen. When all clients use methods to access your object, you're free to change the "insides" however you feel fit as long as it doesn't break the interface you've provided for clients of your component.


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11160
    
  16

To further clarify Nathaniel's point, say you have a variable that is only allowed certain values, such as hours on a clock.
If you let people directly access clock.hours, you have NO control over what they set it to. 18, 397, -46... you can't stop it.
however, if you use a setter method, if they call clock.setHours(96), you can ignore the value, do a mod 12 on it, throw an exception... anything you want. The point is, YOU have control over it.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
Thanks for the input guys! It is much appreciated.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing variables from other classes
 
Similar Threads
Private variables in superclass accessed by subclass
Session Variable and JSTL
Doubt regarding static context
How Static variable handled during concurrent Syncronized Class and Object Call
volatile... is this not correct way?