Java Reference
In-Depth Information
Note A class must implement the java.lang.Cloneable interface or its in-
stances cannot be shallowly cloned via Object 's clone() method—this method
performs a runtime check to see if the class implements Cloneable .(Iwill discuss
interfaceslaterinthischapter.)Ifaclassdoesnotimplement Cloneable , clone()
throws java.lang.CloneNotSupportedException . (Because
CloneNotSupportedException isacheckedexception,itisnecessaryfor List-
ing2-25 tosatisfythecompilerbyappending throws CloneNotSupportedEx-
ception to the main() method's header. I will discuss exceptions in the next
chapter.) String is an example of a class that does not implement Cloneable ;
hence, String objects cannot be shallowly cloned.
Afterassigningthe Employee object'sreferencetolocalvariable e1 , main() calls
the clone() methodonthisvariabletoduplicatetheobject,andthenassignstheres-
ulting reference to variable e2 . The (Employee) cast is needed because clone()
returns Object .
Toprovethattheobjectswhosereferenceswereassignedto e1 and e2 aredifferent,
main() nextcomparesthesereferencesvia == andoutputstheBooleanresult,which
happens to be false. To prove that the Employee object was shallowly cloned,
main() nextcomparesthereferencesinboth Employee objects' name fieldsvia ==
and outputs the Boolean result, which happens to be true.
Note Object 's clone() methodwasoriginallyspecifiedasa public method,
whichmeantthatanyobjectcouldbeclonedfromanywhere.Forsecurityreasons,this
accesswaslaterchangedto protected ,whichmeansthatonlycodewithinthesame
packageastheclasswhose clone() methodistobecalled,orcodewithinasubclass
of this class (regardless of package) can call clone() .
Shallowcloningisnotalwaysdesirablebecausetheoriginalobjectanditsclonerefer
to the same object via their equivalent reference fields. For example, each of Listing
2-25 ' s two Employee objects refers to the same String object via its name field.
Although not a problem for String , whose instances are immutable, changing a
mutableobjectviatheclone'sreferencefieldcausestheoriginal(noncloned)objectto
see the same change via its reference field. For example, suppose you add a reference
fieldnamed hireDate to Employee .Thisfieldisoftype Date with year , month ,
and day instancefields.Because Date isintendedtobemutable,youcanchangethe
contents of these fields in the Date instance assigned to hireDate .
Search WWH ::




Custom Search