I have a newbie question. If I have some global variables that are shared by two classes or more how can I have them in a separate file so that any class can read and update them. Is this possible without using Interfaces?
Asked
Active
Viewed 1,828 times
0
-
possible duplicate of [Global variables in Java](http://stackoverflow.com/questions/4646577/global-variables-in-java) – juergen d Mar 02 '12 at 18:25
2 Answers
1
The best way to do this is to have your shared application state accessible via interface methods, then have an implementing class that holds the variables, and pass this instance of the class to your other classes during construction (which they accept as an instance of the interface).
This is better than using a static class or singleton since it allows you to mock out the functionality of the shared state for testing, improves general code reusability, and allows you to change the implementation and configuration of the shared state without impacting any of the code using it.
E.g.
// Session interface for all application shared state.
public interface ApplicationSession
{
public int getMaxUserLimit();
}
// A backing for the interface (simple in memory version, maybe future versions use a database, who knows).
public class SomeApplicationSession implements ApplicationSession
{
private volatile int maxUserLimit = 0;
public void setMaxUserLimit(int limit) { this.maxUserLimit = limit; }
public int getMaxUserLimit() { return maxUserLimit; }
}
// ClassA uses the supplied session.
public class MyClassA
{
private ApplicationSession session;
public myClassA(ApplicationSession session)
{
this.session = session;
}
}
// usage...
public class MyMain
{
public static void main(String[] args)
{
// Create / get session (ultimately possibly from a factory).
ApplicationSession session = new SomeApplicationSession();
ClassA myClassA = new ClassA(session);
// do stuff..
}
}

Trevor Freeman
- 7,112
- 2
- 21
- 40
-
can you please explain this part to me: ApplicationSession session = new SomeApplicationSession(); – user1064089 Mar 02 '12 at 19:48
-
@user1064089 That is just an example of instantiating an instance of the application session (and then this one instance is shared amongst your other classes at construction time). For this to be useful as written, you would want to declare your set methods in the interface as well (or there is no way to change the variables in the session). – Trevor Freeman Mar 02 '12 at 21:11