2

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.

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
Why wouldn't Bar just use the existing instance of Foo?
How does Bar use that instance that is created in another class?
The instance gets passed to Bar first. Or Bar queries the "another" class, which queries the Foo, which queries the list.
1

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.

Comments

0

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); }

Comments

0

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.

1 Comment

I assume there's a 'not' missing in the first sentence

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.