java - Understanding clone method for non-final classes -


i'm reading j. bloch's effective java , i'm @ section 39 (making defensive copy). mentioned it's not make defensive copies through clone method, because:

note did not use date’s clone method make defensive copies. because date nonfinal, clone method is not guaranteed return object class java.util.date: return an instance of untrusted subclass designed malicious mischief.

the emphasized statement not apparent me. actually, let's consut javadocs. there no reference creating subclasses. can sure this:

this method creates a new instance of class of object , initializes fields contents of corresponding fields of object, if assignment; contents of fields not cloned.

so why did j. bloch create the subclass? couldn't explain how implies javadoc (i can't see on own).

it implicit in javadocs quote: class of "this" object can subclass of declared type of variable referencing object (due polymorphism). clone method protected can invoked in subclass of class.

public class test {     public static void main(string[] args) throws exception {         foo foo = new bar();         foo copyoffoo = createcopyoffoo(foo);         system.out.println(copyoffoo);     }       private static foo createcopyoffoo(foo foo) throws clonenotsupportedexception {         foo clone = (foo) foo.clone();         return clone;     } }  class foo implements cloneable {     @override     protected object clone() throws clonenotsupportedexception {         return super.clone();     } }  class bar extends foo {     private int x = 1;      @override     public string tostring() {         return "bar [x=" + x + "]";     } } 

output:

bar [x=1]


Comments