aspose file tools*
The moose likes Beginning Java and the fly likes Sharing Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sharing Variables" Watch "Sharing Variables" New topic
Author

Sharing Variables

Preetham M
Greenhorn

Joined: Sep 18, 2002
Posts: 12
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

Joined: Sep 29, 2000
Posts: 8521
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.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Preetham M
Greenhorn

Joined: Sep 18, 2002
Posts: 12
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

Joined: Mar 22, 2002
Posts: 1055
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

Joined: Dec 10, 2001
Posts: 7023
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!


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sharing Variables