Java Reference
In-Depth Information
System.out.println("team1 and team5 are NOT equal");
}
This code demonstrates how to make a clone of an object. The resulting output
would be as follows.
Team 3:
Boston
Bandits
Team 4:
Chicago
Wildcats
Team 3:
St. Louis
Bandits
Team 4:
Chicago
Wildcats
Team 5:
Boston
Bandits
team1 and team3 are equal
team1 and team5 are NOT equal
How It Works
There are two different strategies that can be used to copy an object: shallow and deep
copies. A shallow copy can be made that would copy the object without any of its con-
tents or data. Rather, all the variables are passed by reference into the copied object.
After a shallow copy of an object has been created, the objects within both the original
object and its copy refer to the same data and memory. Thus, modifying the original
object's contents will also modify the copied object. By default, calling the su-
per.clone() method against an object performs a shallow copy. The shal-
lowCopyClone() method in the solution to this recipe demonstrates this technique.
The second type of copy that can be made is known as a deep copy , which copies
the object including all the contents. Therefore, each object refers to a different space
in memory, and modifying one object will not affect the other. In the solution to this re-
cipe, the difference between a deep and a shallow copy is demonstrated. First, team1
Search WWH ::




Custom Search