Java Reference
In-Depth Information
Within setVolume(), the println() method is invoked and pushed onto the
call stack. We now have the situation illustrated by the call stack discussed in
the earlier section Method Call Stack . The following is displayed:
Setting the volume to 5
The parameter volume is assigned to the field volume, so now the 5 is in
memory in four different places. The parameter volume is assigned to -5, a
statement I added to emphasize that this is call-by-value. What does changing
volume to -5 do to the argument v that was passed in to volume? It does
nothing to v because volume is a copy of v and not the actual variable v.
Within the setVolume() method, the parameter name is volume, which
also happens to be the name of one of the fields of the Radio class. This
might seem like a naming conflict, but it is okay and is done regularly
in Java. To distinguish between the local variable volume and the field
volume, you must use the this reference whenever referring to the field.
Therefore, using just volume refers to the parameter and using
this.volume refers to the field.
At one point in the ListenToRadio program, the initial volume of 5 was in
four different variables in memory: initialVolume, v, volume, and this.volume.
Keep in mind that the variables volume, v, and initialVolume are local vari-
ables (sometimes aptly referred to as temporary variables). They are allocated
in memory on the call stack, and when the method is done executing, these
variables go away.
For example, when setVolume() is done, the parameter volume goes out of
scope. When turnOn() is done, the parameter v goes out of scope. When main()
is done, initialVolume goes out of scope. But the field volume in the Radio
object stays in memory until the object is garbage collected, which can be long
after these temporary variables have gone away.
After setVolume() finishes, control returns to the turnOn() method, which
invokes setBand(). The setBand() method has a char parameter, and the b in
turnOn() is passed as an argument in to the b parameter of setBand(). There are
now two variables in memory named b, both of value F, but their scopes are
different. The b in turnOn() is not accessible from within setBand(). Nor is the
b in setBand() accessible to the turnOn() method. This is why the value F was
passed into setBand() because the F was needed within the scope of setBand().
The setBand() method prints out the following:
Setting the band to F
Search WWH ::




Custom Search