Java Reference
In-Depth Information
When you pass an object as an argument to a method, the mechanism that applies is called pass-by-referen-
ce , because a copy of the reference contained in the variable is transferred to the method, not a copy of the
object itself. The effect of this is shown in Figure 5-6 .
FIGURE 5-6
Figure 5-6 presumes that you have defined a method, changeRadius() , in the class Sphere , that alters
the radius value for an object, and that you have a method change() in some other class that calls
changeRadius() . When the variable ball is used as an argument to the method change() , the pass-by-ref-
erence mechanism causes a copy of the contents of ball to be made and stored in s . The variable ball just
stores a reference to the Sphere object, and the copy contains that same reference and therefore refers to
the same object. No copying of the actual object occurs. This is a major plus in terms of efficiency when
passing arguments to a method. Objects can be very complex, involving a lot of instance variables. If objects
themselves were always copied when passed as arguments, it could be very time-consuming and make the
code very slow.
Because the copy of the reference from ball refers to the same object as the original, when the
changeRadius() method is called, the original object is changed. You need to keep this in mind when writ-
ing methods that have objects as parameters because this is not always what you want.
In the example shown, the method change() returns the modified object. In practice, you probably want
this to be a distinct object, in which case you need to create a new object from s . You see how you can write
a constructor to do this a little later in this chapter.
NOTE Remember that this only applies to objects. If you pass a variable of a primitive type,
such as int or double to a method for example, a copy of the value is passed. You can modify
the value passed as much as you want in the method, but it doesn't affect the original value.
The Lifetime of an Object
 
 
Search WWH ::




Custom Search