- Recall that:
- Static variables,
also known as class variables,
by ALL objects of the class:
- 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:
- What is the consequence ?
- When the variable x in object1 is changed,
the variable x in object2 is also changed,
and vice versa.
DEMO program showing the
difference between static and instance variables:
- The lifetime of static variables:
- begins to exist at the beginning of the program.
- ceases to exist at the end of the program.
In other words: static variables:
has a lifetime that is the same as the program !!!
- Scope of static variables:
- Same as that of the instance
can only be accessed by
inside the same class,
- public: can be accessed
from any part of the program.
- protected: will be discussed later
- package (default): will also
be discussed later
- WHEN do you need
to use static variables:
- when you need to maintain information
about the objects of the class
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;
balance = 0;
NCount = NCount + 1;
(other methods omitted to save space)
- Each time an object is created, the constructor is called.
The construct here keep track on
the number of BankAccount objects that have been created
by using the
- Suppose we create 2 BankAccount objects as follows:
BankAccount momSaving = new BankAccount();
BankAccount harrysChecing = new BankAccount();
Then the object creation will result in the following situation:
NOTE: the static variable is initialized only once
at the start of the program
Here is a DEMO program:
And an accompanying Test Program:
- Contrast the effect of the static variable
with one where NCount
is an instance variable
(just edit the BankAccount.java 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 !
- Quiz: what will happen if we make the "Balance" variable
- 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