- Sometimes only 1 copy of a particular variable should be shared by all objects of a class.
- A static variable is used for this reason (and others).
- A static variable represents "class-wide" information.
- Static members have class scope:
- A class's public static class members can be accessed via:
- any object of that class
- the class name, using the dot notation (e.g., Integer.parseInt is a public static method of the
Integer class).
- A class's private static class members can be accessed via members of the class.
- Static class members exist even when no objects of that class exist (e.g., Integer.parseInt).
- To access a public or friendly static class member when no objects exist,
prefix the class name and the dot operator to the class member (instance variable or method).
- To access a private static class member when no objects exist,
a public or friendly static method must be used, and must be invoked by prefixing its name with the class name
and the dot operator (e.g., Integer.parseInt() ).
- In the applet below, there may be many employee objects, but only 1 instance variable, count, which holds the
number of employee objects currently existing.
- It is initialized to 0 by default.
- Since it is private, it must be accessed via a method.
- Constructors increment count; the finalizer decrements count.
- count can always be accessed via the expression: Employee.getCount().
- To illustrate the finalizer method, the applet removes the employees via the statements:
e1 = null;
e2 = null;
to force a garbage collection, the garbage collection method is invoked explicitly:
System.gc();
- The System output follows:
Employee object constructor: Susan Baker
Employee object constructor: Bob Jones
Employee object finalizer: Susan Baker
Employee object finalizer: Bob Jones
- A static method cannot access non-static members. Why?
- A static method has no this reference. Why?