[Solved] Java: how to have global values inside a class?


I guess you are looking for something like this:

public class TestClass {
    public final String hallo;
    public static final String halloSecond = "Saluto!";

    TestClass(String hello){
        String hallo = hello;
    }

    public static void main(String[] args) {
        TestClass test = new TestClass("Tjena!");
        System.out.println("I want "Tjena!": " + test.hallo);
        TestClass testSecond = new TestClass("1");
        System.out.println("I want Saluto!:" + test.halloSecond);
        System.out.println("I want Saluto!:" + testSecond.halloSecond);
    }
}

The value of hallo is set in each instance of TestClass. The value of halloSecond is a constant, shared by all instances of the class and visible for the whole app. Note that with this code your IDE/compiler probably gives you a warning upon test.halloSecond – it should be qualified by the class name, like TestClass.halloSecond, rather than an instance name.

Update on global variables: the main problem with global variables is that they make the code

  • harder to understand – if a method uses global variables, you can’t see simply from its signature what data is it actually manipulating
  • harder to test – same method is difficult to test isolated in unit tests, as you have to (re)set all global variables it depends on to the desired state before each unit test
  • harder to maintain – global variables create dependencies, which easily make the code into a tangled mess where everything depends on everything else

In Java everything is inside a class, so you can’t have “classic” global variables like in C/C++. However, a public static data member is still in fact a global variable.

Note that the code sample above, halloSecond is a global constant, not a variable (as it is declared final and is immutable), which alleviates much of these problems (except maybe the dependency issue).

solved Java: how to have global values inside a class?