Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sharing Variables

 
Preetham M
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All:
I have a fundamental question on how can two different classes set a particular variable in the parent class.
Eg:
class A {
int var;
B b = new B();
C c = new C();
}
class B{
void xyz(){
//set var
}
}
class C{
void asd(){
//set var
}
}
If i have 3 classes as i have shown above, is it possible for them to access the variable "int var" in class B abd C and set and reset them maintaining data concurrecy.
Thanks,
Preetham.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the variable in the A class is static then they can each play with it using A.var = whatever;.
If the other classes are inner classes of the A class, then they can get at the var variable no problem.
If the variable in the A class is NOT static then there can be lots of instances of class A, each with it's own copy of the var variable. You would need to pass a reference to the particular instance of the A class that you want affected to the B and C class somehow to let them in on the secret.
So if there is a method in the B class that does something on an A, it should take in a parameter with a reference to that instance. Then if you create a B inside the A class and want to call that instance, you just pass it "this" as the parameter and life is good.
 
Preetham M
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, that was exactly what i did.
However, is it possible for me to sychronize the variable, such that the data integrity is maintained.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Preetham M:
Thank you, that was exactly what i did.
However, is it possible for me to sychronize the variable, such that the data integrity is maintained.

Sure, just use
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Preetham M,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic