Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes passing member field value between classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "passing member field value between classes" Watch "passing member field value between classes" New topic
Author

passing member field value between classes

Richard Teston
Ranch Hand

Joined: Feb 12, 2002
Posts: 89
I have this first class which is an swing gui which displays data from the database. I want to get those data and process them with my second class and as well to my other class. How can the member fields value in the first class can be accesed by other class in the same package, just like a global variable in VB?


The Code is the Programmer
Blake Minghelli
Ranch Hand

Joined: Sep 13, 2002
Posts: 331
You need to check out access modifiers. For example, "protected" allows a field to be accessed by another class in the same package or a subclass.
The other way, which I prefer most of the time, is to keep the class fields "private" and then create "public" methods to get and set the field values, e.g. getters and setters.
For example:

As far as access modifiers go, "public" means that any class can access them.


Blake Minghelli<br />SCWCD<br /> <br />"I'd put a quote here but I'm a non-conformist"
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Either you need to make the variables static so that they can be access using the ClassName, or your second class has to hold a reference to the first class and then it can access the member variables directly if they are accessible (Public for instance). If they are not accessible (if they are private as discussed above), then you need to use a getter method that must exist in the first class and passes out the value of the variable.
In order for the Second class to hold a reference to the first class you would either need to pass it to the constructor when you create the second class, or have a method "SetFirstClassReference" so that you can pass it in.
Then just use
firstClassReference.var1
Note - that it is considered better to keep a classes variables private and use the getters and setters to maintain encapsulation.


"JavaRanch, where the deer and the Certified play" - David O'Meara
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing member field value between classes
 
Similar Threads
Hashtable Performence
Tapestry 5 Page Rendering
Tapestry 5 Reloading
assistance on casting operator
passing parameters to private methods