Global Variables

A class field (static field or instance variable) is declared outside all methods and is global to all methods of the class.  All methods have access to static fields, but static methods, such as main, have no access to this, and therefore no access to instance variables.

One way to provide global variables to a class intended to be an executable program, would be to declare them as static fields and to declare all the methods as static methods.  This scheme has the advantage of not requiring prefixed member names, as in Example 1.  The disadvantage is that only a single version of the program may execute at once, since concurrently executing versions (perhaps with different command line args) would share the same copy of the static fields.

However, static variables are really intended to store values related to a class, not to allow a program to use global variables.  Therefore, it is often wise to declare the class fields as instance variables, to instantiate (create an object of) the class in the main method, and to declare the other methods as instance methods.  The main method then must access the instance members through its local object reference variable, as in Example 2.


Example 1

No prefixing is required when using static variables for global variables.

public class TestGlobalStat {
   private static int testnum;     // static variable
   
   public static void main(String[] args) {
      testnum = 0;                 // init here since value persists
      setNum();
      System.out.println("testnum = " + testnum);
      System.exit(0);
   }
   private static void setNum() {  // static method
      testnum++;
   }
}

Example 2

Here, the global variables are instance variables.

public class TestGlobalInst {
   private int testnum = 0;        // instance variable

   public static void main(String[] args) {
      TestGlobalInst tg = new TestGlobalInst(); 
      tg.setNum();
      System.out.println("testnum = " + tg.testnum);
      System.exit(0);
   }
   private void setNum() {         // instance method
      testnum++;
   }
}

Copyright © 2003 The Stevens Computing Services Company, Inc.  All rights reserved.