I have a Server and ServerConnection classes where a user is connected through the Server and then a ServerConnection instance is created for him and the user is maintained there.
In Server I have some data and I would like the ServerConnection instance to be able to access it.
How it's possible?
The ServerConnection instance is created inside the Server class so it's not easy to figure out how to go up one level (to Server class) to get data from it.
If ServerConnection is an inner class of Server, you can directly access the Server instance's fields (even if it is shadowed):
public class Server {
private String data;
public class ServerConnection {
private int data; //shadows Server.data
public void connect() {
//access Server.data of the Server instance associated with this instance
Server.this.data = "xyz"; //Note that you also have write access, so that might be dangerous
...
}
}
}
A better approach might be to pass the Server instance to the ServerConnection and expose the data by getters:
public class ServerConnection {
private Server server;
public ServerConnection(Server s) {
server = s;
}
public void connect() {
String serverData = server.getData();
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With