Java Reference
In-Depth Information
PigLatin
PigLatinTranslator
+ main (args : String[]) : void
+ translate (sentence : String) : String
— translateWord (word : String) : String
— beginsWithVowel (word : String) : boolean
— beginsWithBlend (word : String) : boolean
FIGURE 7.4 A UML class diagram for the PigLatin program
Method Parameters Revisited
Another important issue related to method design involves the way parameters
are passed into a method. In Java, all parameters are passed by value. That is,
the current value of the actual parameter (in the invocation) is copied into the
formal parameter in the method header. We mentioned this issue in Chapter 4;
let's examine it now in more detail.
Essentially, parameter passing is like an assignment statement, assigning to the
formal parameter a copy of the value stored in the actual parameter. This issue
must be considered when making changes to a formal parameter inside a method.
The formal parameter is a separate copy of the value that is passed in, so any
changes made to it have no effect on the actual parameter. After control returns to
the calling method, the actual parameter will have the same value as it did before
the method was called.
However, when we pass an object to a method, we are actually passing a refer-
ence to that object. The value that gets copied is the address of the object. Therefore,
the formal parameter and the actual parameter become aliases of each
other. If we change the state of the object through the formal param-
eter reference inside the method, we are changing the object referenced
by the actual parameter, because they refer to the same object. On
the other hand, if we change the formal parameter reference itself (to
make it point to a new object, for instance), we have not changed the
fact that the actual parameter still refers to the original object.
KEY CONCEPT
When an object is passed to a
method, the actual and formal
parameters become aliases.
The program in Listing 7.15 illustrates the nuances of parameter passing.
Carefully trace the processing of this program and note the values that are output.
The ParameterTester class contains a main method that calls the changeValues
method in a ParameterModifier object. Two of the parameters to changeValues
are Num objects, each of which simply stores an integer value. The other parameter
is a primitive integer value.
 
Search WWH ::




Custom Search