Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

passing member field value between classes

 
Richard Teston
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic