Static variables (class variables)

  1. Recall that: instance variables are NOT shared among objects:

  2. Static variables, also known as class variables, are SHARED by ALL objects of the class:

  3. Suppose we have the following class:

        public class myClass
           int a;        // instance variable
           int balance;  // instance variable
           static int x; // static (or class) variable  

    and we define 2 objects on this class:

         myClass object1 = new myClass();   
         myClass object2 = new myClass();

    then the objects will share variable x:

  4. What is the consequence ?

    DEMO program showing the difference between static and instance variables: click here

  5. The lifetime of static variables:

    In other words: static variables: has a lifetime that is the same as the program !!!

  6. Scope of static variables:

  7. WHEN do you need to use static variables:

  8. Example of a situation that you need to use a static variable

    Example: Keeping a count on the number of object created so far
          public class BankAccount
             private double balance;
             private static int NCount = 0;
             public BankAccount()
    	    balance = 0;
    	    NCount = NCount + 1;
    	 (other methods omitted to save space)

  9. Contrast the effect of the static variable with one where NCount is an instance variable (just edit the file and remove the static keyword and run it)

    The result is explained by the following figure:

    Note: because NCount is now an instance variable and you will create one more NCount each time you call "new BankAccount()".

    Also: the newly created NCount instance variable will be initialized to 0 each time it is created !

  10. Quiz: what will happen if we make the "Balance" variable static ????

  11. Global variables in C/C++ vs. Static variable in Java:

    • Java's static variables are like global variables in C or C++
    • Global variable start to exist at the start of the program...
    • and continue to exist until the end of the program
    • Global variables are accessible from anywhere in the program (entire lifetime of the program)
    • Only difference is in Java, you need to specify where (which class) they are defined.
    • Example: click here
    • The equivalent C program: click here