Programming and Problem Solving with Java

(やまだぃちぅ) #1
5.3 Mutable and Immutable Objects | 245

Argument Parameter
Call
PrintStream
System.out

PrintStream
param 1

PrintStream
param 1

PrintStream
param 1

PrintStream
System.out

PrintStream
System.out

Address 2 015

Address 2 015 Address 2 015

Address 2 015

2015

Address 2 015

During execution

Return

param 1 .print("Java");

Memory before call
Address Contents
"some text"
"other text"
"more text"

2015

Memory after call
Address Contents
"some text"
"other text"
"more text"
"Java"

Figure 5.9 The Effect of Changing the Fields of a Reference Type Parameter


can use his or her copy of that number to perform some task. The person could also replace
the number with a different one. When done, the individual throws away that paper and your
paper remains unchanged.
Now suppose your slip of paper contains the address of a house (a reference type). The
other person can use his or her copy of the address to go look at the house. If the person
changes the address on that slip of paper (assigns a new value to the reference type param-
eter), then he or she can go to a different house, but would no longer have the address of the
first house. When the other person is done, he or she throws away the paper. Your slip of pa-
per still has the original address, so you can go and look at the house; you find it unchanged.
Finally, suppose that you again have an address on your slip of paper, but this time
the person goes to the house and, instead of just looking at it, goes inside and rearranges
the furniture. When done, the other party throws away his or her paper, but your paper
still has the address of the house. When you go to the house, you find that its contents
have changed.
In every case, your slip of paper remained unchanged. In Java, the argument is never af-
fected by a method call. But in the last situation, the method changed the object at the ad-
dress it was given. So even though the address in the argument remained untouched, the
object to which it refers was altered. Whenever you are writing a method that changes a
reference parameter, and you are unsure about how the operation will behave, stop and ask
yourself, “Am I going inside the house, or am I going to a different address?”

Free download pdf