Calling a method in another object
Enrique
Posts: 90
Hi,
·
Say you have three objects: one we will call Top, which will instantiate objects A and B. Can the top object call a method in B and then can this method in B call a method in A?
·
Example:
·
Thanks,
Enrique
·
Say you have three objects: one we will call Top, which will instantiate objects A and B. Can the top object call a method in B and then can this method in B call a method in A?
·
Example:
·
{{ File Top.spin }} obj OA:"A" OB:"B" pub main OB.MethodB
{{ File A.spin }} pub MethodA ' does something
{{ File: B.spin }} pub MethodB ' does something ' somehow calls MethodA in object OA
Thanks,
Enrique
Comments
The only way to call a method in object A from object B is to have a declaration of the object in B (like OBJ OA:"A"). If object A has its own VAR variables, these will be duplicated in each copy (instance) of object A. There are some objects in the Object Exchange that only have variables in a DAT section and this is shared (common) among all copies of the object. Here's one example: obex.parallax.com/objects/189/.
If your A object is a "singleton", then you can instantiate the A object within the B object as well as the Top object and they will both refer to the same object. Then you can call methods on A from both Top and B.
To make an object a "singleton", put all of the variables in that object in the DAT section instead of the VAR section. When an object is instantiated at more than one place in a program, only one copy of the code and the DAT section are used, but the compiler will make a copy of the VAR section for each instance of the object. If the variables are all in DAT, then all instances of the object are the same.
I have done this with the FullDuplexSerial object because I wanted to share the same serial interface at different levels within the program. I've also done it with the TV text object so I could share the display with several different objects.
Keep in mind that the object has to be coded to allow this. If you are using someone else's object, you may have to make a modifications to it to make it a singleton. Also, if the object has a start() or init() routine, that should only be called once, i.e., you wouldn't call start() from both Top and B.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
·"I have always wished that my computer would be as easy to use as my telephone.· My wish has come true.· I no longer know how to use my telephone."
- Bjarne Stroustrup
-Phil
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
'Just a few PropSTICK Kit bare PCBs left!
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
·"I have always wished that my computer would be as easy to use as my telephone.· My wish has come true.· I no longer know how to use my telephone."
- Bjarne Stroustrup
Post Edited (Ken Peterson) : 12/1/2008 6:43:54 PM GMT