Information Technology Reference
In-Depth Information
The preceding code produces the following output:
d1: Mem1= 2, Mem2= 4
d2: Mem1= 15, Mem2= 17
d1: Mem1= 2, Mem2= 17
Lifetimes of Static Members
Instance members come into existence when the instance is created, and go out of existence
when the instance is destroyed. Static members, however, exist and are accessible even if there
are
no instances
of the class.
Figure 6-4 illustrates a class
D
, with a static field,
Mem2
. Although
Main
does not define any
instances of the class, it assigns the value
5
to the static field and prints it out.
Figure 6-4.
Static field with no class instances
The code in Figure 6-4 produces the following output:
Mem2 = 5
■
Note
Static members exist even if there are no instances of the class.