• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

passing member field value between classes

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
What's wrong? Where are you going? Stop! Read this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic