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

variable accessibility

 
Krithika Beri
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a variable in one class and i want to be able to edit that variable in another class such that when i make changes in class2 is should be updated in class1. Please help.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The brute force way to do this is to simply provide a setter method:


However, it's not a good idea to just go around blindly providing that kind of direct access without a good reason. Sometimes it makes sense to do so, but often times it's better design to just give C1 real behavior through methods, and let those methods update C1's member variables as appropriate. As much as it practical, the details of C1's state should stay hidden from users of C1.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48957
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should not have the same value in two classes. You should have the value in one class and one only. It should have one copy and one only. If you need the other class to use it, it can be provided by a public getXXX method. If you really need to signal the other object about a change, you are getting into more advanced practices: look for the observer pattern.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic