Java Reference
In-Depth Information
The program in Listing 8.11 demonstrates the difference between passing a primitive type
value and passing a reference value.
L
ISTING
8.11
TestPassObject.java
1
public class
TestPassObject {
2
/** Main method */
3
public static void
main(String[] args) {
4
// Create a Circle object with radius 1
5 CircleWithPrivateDataFields myCircle =
6
new
CircleWithPrivateDataFields(
1
);
7
8
// Print areas for radius 1, 2, 3, 4, and 5.
9
int
n =
5
;
10
11
12
// See myCircle.radius and times
13 System.out.println(
"\n"
+
"Radius is "
+ myCircle.getRadius());
14 System.out.println(
"n is "
+ n);
15 }
16
17
/** Print a table of areas for radius */
18
public static void
19
printAreas(myCircle, n);
pass object
printAreas(
object parameter
CircleWithPrivateDataFields c,
int
times)
{
20 System.out.println(
"Radius \t\tArea"
);
21
while
(times >=
1
) {
22 System.out.println(c.getRadius() +
"\t\t"
+ c.getArea());
23 c.setRadius(c.getRadius() +
1
);
24 times——;
25 }
26 }
27 }
Radius Area
1.0 3.141592653589793
2.0 12.566370614359172
3.0 29.274333882308138
4.0 50.26548245743669
5.0 79.53981633974483
Radius is 6.0
n is 5
The
CircleWithPrivateDataFields
class is defined in Listing 8.9. The program passes
a
CircleWithPrivateDataFields
object
myCircle
and an integer value from
n
to
invoke
printAreas(myCircle, n)
(line 9), which prints a table of areas for radii
1
,
2
,
3
,
4
,
5
, as shown in the sample output.
Figure 8.18 shows the call stack for executing the methods in the program. Note that the
objects are stored in a heap (see Section 6.6).
When passing an argument of a primitive data type, the value of the argument is passed. In
this case, the value of
n
(
5
) is passed to
times
. Inside the
printAreas
method, the content
of
times
is changed; this does not affect the content of
n
.
When passing an argument of a reference type, the reference of the object is passed. In this
case,
c
contains a reference for the object that is also referenced via
myCircle
. Therefore,
changing the properties of the object through
c
inside the
printAreas
method has the same
effect as doing so outside the method through the variable
myCircle
. Pass-by-value on refer-
ences can be best described semantically as
pass-by-sharing
; that is, the object referenced in
the method is the same as the object being passed.
pass-by-sharing