What is the best way to share data between separate classes in Java? I have a bunch of variables that are used by different classes in separate files in different ways. Let
I guess the answer to your question is the Design Pattern called Singleton. It basically allows you to get and exploits the same (and unique) instance of a class whenever you want in your system.
This is its implementation (please forgive possible syntax errors, I did not compile it):
class Container{
//eventually provides setters and getters
public float x;
public float y;
//------------
private static Container instance = null;
private void Container(){
}
public static Container getInstance(){
if(instance==null){
instance = new Container();
}
return instance;
}
}
then if elsewhere in your code you import the Container you can write for example
Container.getInstance().x = 3;
temp = Container.getInstance().x;
and you will affect the attributes of the unique container instance you have in your system
In many cases it is however better to use the Dependency Injection pattern as it reduces the coupling between different components.