Java Reference
In-Depth Information
LISTING 3.4
The Full Text of
RefTester.java
1: import java.awt.Point;
2:
3: class RefTester {
4: public static void main(String[] arguments) {
5: Point pt1, pt2;
6: pt1 = new Point(100, 100);
7: pt2 = pt1;
8:
9: pt1.x = 200;
10: pt1.y = 200;
11: System.out.println(“Point1: “ + pt1.x + “, “ + pt1.y);
12: System.out.println(“Point2: “ + pt2.x + “, “ + pt2.y);
13: }
14: }
Here is this program's output:
3
Point1: 200, 200
Point2: 200, 200
The following takes place in the first part of this program:
Line 5
—Two
Point
variables are created.
n
Line 6
—A new
Point
object is assigned to
pt1
.
n
Line 7
—The value of
pt1
is assigned to
pt2
.
n
Lines 9-12 are the tricky part. The
x
and
y
variables of
pt1
are both set to
200
, and then
all variables of
pt1
and
pt2
are displayed onscreen.
You might expect
pt1
and
pt2
to have different values. However, the output shows this is
not the case. As you can see, the
x
and
y
variables of
pt2
also were changed, even
though nothing in the program explicitly changes them. This happens because line 7
creates a reference from
pt2
to
pt1
, instead of creating
pt2
as a new object copied
from
pt1
.
pt2
is a reference to the same object as
pt1
; this is shown in Figure 3.1. Either variable
can be used to refer to the object or to change its variables.
FIGURE 3.1
References to
objects.
Point object
x: 200
y: 200
pt1
pt2