This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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?
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"
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
subject: passing member field value between classes