-
Objects sharing data
I am working on an assignment where I write one class that extends a pre-made class. I only have control of the one class file I create and I was wondering if there is any way to share data between all the different objects created from my class? Can I create a file have them all read and edit it? Or possibly have some kind of global array?
Thanks!
-
Re: Objects sharing data
You can pass these instances of other classes a reference to your data. You do this in their constructor or methods. Once they have this reference they haz your data.
An alternative to consider: this class of yours could have methods that the instances of these other classes can call to have things done with the data without actually getting their hands on the data itself. Why? Because when lots of instances have access to the data it can become very hard to control and have confidence in the integrity of the data. Your bank will likely give you an electronic way of making deposits and withdrawls (methods) but they don't give you access to the "balance" data. And this is true even when you are the author of these other classes. Give other classes the abilty to tell you to do something with the data, don't let them get their careless or anarchic mitts on the data itself: there's more control that way.
----
All that is as relevant (or not) whether or not your class subclasses somethng else. So perhaps I'm not getting something about the actual situation you face and what your're trying to do.
-
Re: Objects sharing data
If you are interested, this is the assignment:
CSE142 handout #18
It's a game where I am competing with other extensions of the critter class with various attributes.
I am writing one class of my own design that is an extension of the critter class. I can control direction, interactions and look at the spaces around each object. Ideally I want all my objects to gather as much data about their surroundings as possible and be able to share and see the data from all my other objects. So as you see all the code I have access to is my Husky.class file when the graders run it.