Java Reference
In-Depth Information
It is very important that you remember that the
box
variable does not contain the
object. It refers to the object. You can have two object variables refer to the same
object:
Rectangle box2 = box;
Now you can access the same
Rectangle
object both as
box
and as
box2
, as
shown in
Figure 17
.
Multiple object variables can contain references to the same object.
However, number variables actually store numbers. When you define
int luckyNumber = 13;
then the
luckyNumber
variable holds the number 13, not a reference to the number
(see
Figure 18
).
You can see the difference between number variables and object variables when you
make a copy of a variable. When you copy a primitive type value, the original and the
copy of the number are independent values. But when you copy an object reference,
both the original and the copy are references to the same object.
Number variables store numbers. Object variables store references.
Consider the following code, which copies a number and then changes the copy (see
Figure 19
):
int luckyNumber = 13;
int luckyNumber2 = luckyNumber;
luckyNumber2 = 12;
Now the variable
luckyNumber
contains the value 13, and
luckyNumber2
contains 12.
Now consider the seemingly analogous code with
Rectangle
objects.
Rectangle box = new Rectangle(5, 10, 20, 30);