Java Reference
In-Depth Information
public static void
incrementY()
{
y++;
}
}
Suppose that you have the following declaration:
Illustrate illusObject =
new
Illustrate();
The reference variable
illusObject
can access any
public
member of the
class
Illustrate
.
The method
incrementY
is
static
and
public
, so the following statement is legal:
Illustrate.incrementY();
Similarly, because the data member
count
is
static
and
public
, the following state-
ment is legal:
Illustrate.count++;
In essence,
public static
members of a
class
can be accessed either by an object, that is, by
using a reference variable of the
class
type, or using the
class
name and the dot operator.
8
Suppose that you have a
class
, say,
MyClass
, with data members (
static
and non-
static
). When you instantiate the objects of type
MyClass
, only the non-
static
data
members of the
class
MyClass
become the data members of each object. What about
the memory for the
static
data members of
MyClass
? For each
static
data member
of the
class
, Java allocates memory space only once. All
MyClass
objects refer to the
same memory space. In fact,
static
data members of a
class
exist even when no object
of the
class
type is instantiated. Moreover,
static
variables are initialized to their
default values. You can access the
public static
data members outside the
class
,as
explained in the previous section.
The following example further clarifies how memory space is allocated for
static
and
non-
static
data members of a class.
Suppose that you have the
class
Illustrate
, as given in Example 8-6. Then, memory
space exists for the
static
data members
y
and
count
.
Consider the following statements:
Illustrate illusObject1 =
new
Illustrate(3);
//Line 1
Illustrate illusObject2 =
new
Illustrate(5);
//Line 2
The statements in Lines 1 and 2 declare
illusObject1
and
illusObject2
to be
reference variables of type
Illustrate
and instantiate these objects (see Figure 8-15).
Search WWH ::
Custom Search