Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access to another classs' elements(variables)?

 
sahar sa
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI there,
I want to have access to a variable which is declared in another class.
e.g. I have class A and class B. I have a HashMap X in class A and I need to have access to this map from class B. for example I want to call X.remove() from inside class B.
how can I do this?
I have tried to declare my HashMAp public in class A and then import class A in class B , but still I dont have access to my X hashmap.
any suggestion would be greatly appreciated.

thanks,
sahar
 
david j greenfield
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see below code snippet, i would suggest using encapsulation, its always good practice.

Here is my first class test, It has a TextField variable which is set to private (you could set it to public and access it directly, but that wouldn't be good OO design). I created a public method setTextField(String str), which gives access to the setText method of the TextField.




Here is my second class test2, who will access the class tests public method TextField, and pass a string into the setTextField method. Which will update the TextField.



Hope this helps, if its not totally clear please let me know. Also, it may help if you posted a snippet of what youre working on, or an example.

~ea
 
Maneesh Godbole
Saloon Keeper
Posts: 11027
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
energy alchemist wrote:

Please check your private messages for an important administrative matter
 
sahar sa
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear energy alchemist,
That was so clear! I completely understand!

Thankyou so much!!!

Sahar.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why have you declared that method and the field static?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic