Java Reference
In-Depth Information
Similarly,
point1++
has no Java meaning; it suggests that
point1
—1000—
should be increased to 1001, but in that case it might not be referencing a
valid
Point
object. Many languages (e.g., C++) define the
pointer,
which
behaves like a reference variable. However, pointers in C++ are much more
dangerous because arithmetic on stored addresses is allowed. Thus, in C++,
point1++
has a meaning. Because C++ allows pointers to primitive types, one
must be careful to distinguish between arithmetic on addresses and arithmetic
on the objects being referenced. This is done by explicitly
dereferencing
the
pointer. In practice, C++'s unsafe pointers tend to cause numerous program-
ming errors.
Some operations are performed on references themselves, while other
operations are performed on the objects being referenced. In Java, the only
operators that are allowed for reference types (with one exception made for
String
s) are assignment via
=
and equality comparison via
==
or
!=
.
Figure 2.2 illustrates the assignment operator for reference variables. By
assigning
point3
the stored value of
point2
, we have
point3
reference the same
object that
point2
was referencing. Now,
point2==point3
is
true
because
point2
and
point3
both store 1024 and thus reference the same object.
point1!=point2
is also
true
because
point1
and
point2
reference different objects.
The other category of operations deals with the object that is being ref-
erenced. There are only three basic actions that can be done:
1.
Apply a type conversion (Section 1.4.4).
2.
Access an internal field or call a method via the dot operator (
.
)
(Section 2.2.1).
3.
Use the
instanceof
operator to verify that the stored object is of
a certain type (Section 3.6.3).
The next section illustrates in more detail the common reference operations.
figure 2.2
The result of
point3=point2
:
point3
now
references the
same object as
point2.
1000
( 0, 0 )
point1
( 0, 0 )
1024
( 5, 12 )
(at 1000)
3200
point2
= 1024
point1
= 1000
point3
= 1024
point2
( 5, 12 )
3600
(at 1024)
5124
point3
Search WWH ::
Custom Search