Information Technology Reference
In-Depth Information
Static Fields
Besides instance fields, classes can also have
static fields
.
A static field is
shared
by all the instances of the class.
-
With a static field, all the instances access the same memory location.
-
If the value of the memory location is changed by one instance, the change is visible
to all the instances.
The
static
modifier is used to declare a field static, as follows:
class D
{
int Mem1; // Instance field
static int Mem2; // Static field
↑
Keyword
}
For example, the code in Figure 6-3 declares class
D
with static field
Mem2
and instance field
Mem1
.
Main
defines two instances of class
D
.
Because
Mem2
is static, both instances of class
D
share a single
Mem2
field.
f
Mem2
is changed in one instance, it is changed in the other as well.
Member
Mem1
is not declared
static
, so each instance has its own copy.
Figure 6-3.
Static and non-static data members