Java Reference
In-Depth Information
name = "Superwoman"
address = 2000
name = "Superwoman"
address = 2000
location: 2000
object c2
object c1
streetName = "Main"
number = 123
object address
FIGURE 8.7:
Cloning example.
public
String toString()
{
return
number+
""
+streetName ;
}
public void
changeAddress(String streetName ,
int
number)
{
this
. streetName = streetName ;
this
. number = number ;
}
}
public class
CloneTest
{
public static void
main(String [] args)
throws
Exception
{
Address address =
new
Address(
"Main"
,123) ;
FictionalCharacter c1 =
new
FictionalCharacter(
"Superwoman"
,
address) ;
FictionalCharacter c2 = (FictionalCharacter) c1. clone() ;
address . changeAddress(
"Main"
, 235) ;
System. out . println (c2) ;
}
}
Figure 8.7 depicts what happens. We call
super.clone()
to perform the cloning of our
fictional character object. However, the default
clone
method inside the
Object
class does
not know anything about the structure of an object of type
FictionalCharacter
.Itsimply
copies all the data. As a result, both
c1
and
c2
will contain the same object of type
Address
.
Now, if this address is modified, the change will affect both objects.
Shallow copy
happens when we copy the data of an object, but we do not make
copies of the inner objects. Shallow copy is dangerous because changes to an inner
object of one class leads to changes of the same inner object of the other class. The
default
clone
method inside the
Object
class performs shallow copy. If we want to
perform deep copy, we need to override the method.