Cloning Objects: Part Two
By Bruce Eckel
Last month, I discussed using the clone() method to create a copy of an object. Knowing how to implement clone() lets you create classes that can be passed by value, as in
Listing One. The structure of clone() and the toString() method necessary for easy printing should now be familiar. For simplicity, int i is "friendly," so it can be accessed directly.
In PassByValue, the two methods g() and f() demonstrate two different approaches to passing by value. g() passes by reference, modifying the outside object and returning a reference to it; f() clones the argument, thereby decoupling it and leaving the original object alone. It can then perform other tasks even return a handle to this new object without any ill effects to the original.
The act of passing by value actually occurs in the statement: v=(Value)v.clone(). Although this is a rather strange coding idiom, it is perfectly feasible in Java because everything that has a name is a handle. Thus, the handle v is used to clone() a copy of what it refers to. This returns a handle to the base type Object (because it's defined that way in Object.clone()), which must then be cast to the proper type.
In
|