tags:

views:

96

answers:

4

If I want to create a form that adds people to a List, how do I have access to that List from another class? Where would I define that List so other classes can access the members, the size, etc? For example, if I have Class Foo that has the GUI for my form, along with buttons to add and remove people to the List, it would make sense to me to declare the List as a private instance variable of Class Foo. But then if I have another class, Class Bar, how does it get the values that are currently in that List to update some other graphical components? Or is that the wrong place to declare the List in general? Thanks.

+2  A: 

Other classes should not be touching the List. They should query the Foo for information about the List, at which point the Foo can talk to its private List.

Ignacio Vazquez-Abrams
Can you give me an example of how that would work? I guess I'm getting confused since I only declare one object of type Foo, then if I had a function that returned the size of the List, I would have to create a new object from my Bar class to use the member function getSize right?
Crystal
Why wouldn't Bar just use the existing instance of Foo?
Ignacio Vazquez-Abrams
How does Bar use that instance that is created in another class?
Crystal
The instance gets passed to Bar first. Or Bar queries the "another" class, which queries the Foo, which queries the list.
Ignacio Vazquez-Abrams
A: 

You should not give them direct access to private variable (actually the outside classes will not even see it).

To give/modify the list information, the Foo class should have methods to interact with the private list. For instance, you can have a method called getSize() that will return the size of the list.

Pran
I assume there's a 'not' missing in the first sentence
seanizer
You are right. I made the change.
Pran
A: 

In the simplest case use a getter function:

List getList () { return list; }

Then other objects can operate on the list directly. To be more object-oriented, wrap the list-access methods in your object, and never directly return the list object, eg:

Object getItemFromList (int i) { return list.get(i); }
S..
+1  A: 

As I said in my answer to your previous question, I don't think a list of data belongs inside a gui component. I think you should have an application core, a service if you want, that you can use from the gui component, without coupling the two.

That way it's possible to create a web client, a command line client, an SWT client etc, without changing the core application code. You just write a new GUI and inject the service there. A GUI should have access to services but not be one.

seanizer