View Full Version : Making Variables/Objects global across classes

12-10-2007, 03:46 PM
Im writing a MIDlet app that contains some 5 classes. There are some variables and objects (date and filename for example) that is unique across the classes and to make this variables/objects assessible to the each of the class, I simply pass it as a parameter to the constructor. This however looks quack and does not support flexibility as I have to touch the constructors of each of the classes and their different instantiation points anytime I find out there is need to add another 'global' variable/object.
Is there anyway I can make the variables/objects 'Globally' accessible to all the classes without having to pass them as parameters?

12-10-2007, 04:10 PM
If they are stored in one class, why not use get/set methods to access/manipulate the variables as needed?

12-14-2007, 09:26 AM
If they are stored in one class, ...
The app has 5 different classes

12-14-2007, 01:59 PM
You can make the variables static class variables and access them with static get/set methods. Using static variables and methods will keep the variables unique across instances of that class.

For example:

public class MyClass
private static int myVariable = 5;

public static void setMyVariable(int value)
myVariable = value;

public static int getMyVariable()
return myVariable;
You would access this from your other class by:


int x = MyClass.getMyVariable();

12-14-2007, 02:50 PM
The first thing I would do is review you design of your code, having that many classes being dependent on each other may not be good style.

Alternately, you could do as Brad mentioned and make some of your classes inner-classes of another so that they have access to needed variables.
As an example, I've provided skeleton code from one of my midlets.

public class CameraMIDlet extends MIDlet
implements CommandListener, Runnable {

private Display mDisplay; //Main Midlet display
...more midlet code...

class PicCountCanvas extends Canvas
implements CommandListener {

} //PicCountCanvas Class

class RecordAudio extends Thread {
public void run(){
}//RecordAudio Class

}//CameraMIDlet Class

All of these classes would then have access to the mDisplay variable declared by the CameraMIDlet Class.