Java - Sharing data across classes
-
Hi, I'm creating a lobby application (for a small game) in Java but I have a problem: - The app opens a server socket and waits for clients to connect. - For every client that connects a new client-class is created which communicates with the client and receives info, like a username. My problem is how to share the info (like the username) with all the other client-classes? Every client needs to see a list of all connected users, one user should be able to send a message to another user and so on.
-
Hi, I'm creating a lobby application (for a small game) in Java but I have a problem: - The app opens a server socket and waits for clients to connect. - For every client that connects a new client-class is created which communicates with the client and receives info, like a username. My problem is how to share the info (like the username) with all the other client-classes? Every client needs to see a list of all connected users, one user should be able to send a message to another user and so on.
I think you can accomplish this with a class variable. A class variable is on that only has one instance and is shared between all copies of the class. It is a variable in the class that is declared outside the scope of all the methods of the class and has the static modifier in it's declaration. An example:
public class ClientClass
{
public static Vector userNames = new Vector(0, 1);public ClientClass(String userName)
{
userNames.add(userName);
}public Vector getUserNames()
{
return userNames;
}}
Use of above:
ClientClass client1 = new ClientClass("user 1");
ClientClass client2 = new ClientClass("user 2");
Vector users1 = client1.getUserNames();
Vector users2 = client2.getUserNames();In the above both users1 and users2 should be the same.