Java Reference
In-Depth Information
TIP: Deep Copy versus Shallow Copy
In the previous two subsections, we contrasted the following two ways of defining the
method getBirthDate (Display 5.19):
public Date getBirthDate()
{
return new Date(born);
}
public Date getBirthDate() //Unsafe
{
return born; //Not good
}
As we noted, the first definition is the better one (and the one used in Display 5.19).
The first definition returns what is known as a deep copy of the object born . The sec-
ond definition returns what is known as a shallow copy of the object born .
A deep copy of an object is a copy that, with one exception, has no references
in common with the original. The one exception is that references to immutable
objects are allowed to be shared (because immutable objects cannot change in
any way and so cannot be changed in any undesirable way). For example, the first
definition of getBirthDate returns a deep copy of the date stored by the instance
variable born . So, if you change the object returned by getBirthDate , that does
not change the Date object named by the instance variable born . The reason is
that we defined the copy constructor for the class Date to create a deep copy (Dis-
play 5.20). Normally, copy constructors and accessor methods should return a
deep copy.
Any copy that is not a deep copy is called a shallow copy . For example, the second
definition of getBirthDate returns a shallow copy of the date stored by the instance
variable born .
We will have more to say about deep and shallow copies in later chapters.
deep copy
shallow copy
Never Return a Reference to a Mutable Private Object
A class that contains mutator methods or other methods, such as input methods, that can
change the data in an object of the class is called a mutable class , and objects of the class
are called mutable objects . When defining accessor methods (or almost any methods),
your method should not return a reference to a mutable object. Instead, use a copy con-
structor (or other means) to return a reference to a completely independent copy of the
mutable object.
Search WWH ::




Custom Search