If i create an object in Class1 and save some data in that object in Class1, how can i access that same data in Class2? Here's a code sample that should clarify my situation:

Class1.java:

public class Class1 implements Runnable {
    public ClientArray ca;

        public Class1(int port) throws IOException {
        ca = new ClientArray();
    Client client = new Client(socket);
    ca.setArraySize();
    ca.addClient(client);
    }

Class2.java:

    protected void doInSession() {


    //need to access that same ClientArray ca here that i created in Class1!
        System.out.println(ca.getClient() + "clietttttttttttttt");
    }


ClientArray.java:

public class ClientArray {
    Client[] ClientArray;

    public void ClientArray() {
    }

    public void setArraySize() {
        System.out.println("new ca");
        ClientArray = new Client[100];
    }


    public void addClient(Client client) {
        ClientArray[0] = client;

    }
    public Client getClient() {
        System.out.println(ClientArray[0].getSocket() + " aaaaaaaaaaaaaaaaaa");
        return ClientArray[0];
    }

}

Add a method in Class1 that returns ca to its caller.
What is the relationship between Class1 and Class2? Does either have a reference to the other?

Edited 4 Years Ago by NormR1

No they don't have reference, and i don't understand how could i call that method from Class1, since i would have to access that same instance of Class1 where ca is created.

It looks like i can achieve what i want by creating ClientArray like this:

   ca = ClientArray.getInstance();

and getInstance looks like this:

   public static ClientArray getInstance() {
                if (instance==null)
                  instance = new ClientArray();
        return instance;
    }

Making it static means there is only ONE instance of the ClientArray class to be accessed.

I don't think that will be a problem, since ClientArray class is only supposed to be a sort of "database" of currently connected clients.

Define a static Class1 object and inside the constructor's declaration for Class1 assign this to the static object.Then you can access the Class1 object by simply calling Class1.<static_obj_ref_name>.<method_name()>/<var_name>

This article has been dead for over six months. Start a new discussion instead.