0

Possible Duplicate:
Global variables in Java

How to create a list of global variables that can be accessible from different classes? Should I create a class of global variables...?

Community
  • 1
  • 1
You Kuper
  • 1,113
  • 7
  • 18
  • 38

5 Answers5

2

you can say

    public  class GlobalVariables{
    public static final Integer INT_VAR=12;
    public static final String STR_VAR="abcd";
//  public static final List<SomeObject> someObjectList=new ArrayList<SomeObject>()// this can be populated using some method later.
    }

you can also use interfaces and enums for declaring global variables..

Anantha Sharma
  • 9,920
  • 4
  • 33
  • 35
1

Personally, I would create a class containing public static variables and then use import static MyClass.* in each class the variables are required.

import static MyClass.*;

class MainClass {
    void someMethod() {
        // using "import static" there's no need to do
        // int x = MyClass.SomeStaticInt;
        int x = SomeStaticInt;
        System.out.println(x);
    }
}
Joe Axon
  • 164
  • 7
1

Should I create a class of global variables...?

Yes. create a static class having public static final fields.

final will mark those fields as constants.

Azodious
  • 13,752
  • 1
  • 36
  • 71
1

you can create one class called ConstantCodes.java

Now declare your variable in this class has follows,

public class ConstantCodes
{
      public static String PublicVariable = "I am public variable"; 
}

Now you can above variable anywhere from your project using below line,

String myStr = ConstantCodes.PublicVariable;
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • If I don´t know apriori the values of global variables and want to define them from JTextField (SWING), then can I do something like this: ConstantCodes.PublicVariable = Integer.parse(txtBox.getText().toString()); ? – You Kuper Jan 24 '12 at 11:52
  • yes, you can but in the starting of the class. just store the values in db & try to retrieve from it, if no value found then display default one. got it ? – Lucifer Jan 24 '12 at 11:55
0

Use a interface or enum for constants declaration.

Pokuri
  • 3,072
  • 8
  • 31
  • 55