From this Artima article on clone vs copy constructor:
Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor. There are no guarantees that it preserves the invariants established by the constructors. There have been lots of bugs over the years, both in and outside Sun, stemming from the fact that if you just call super.clone repeatedly up the chain until you have cloned an object, you have a shallow copy of the object.
What does Joshua Bloch mean by extra-linguistic?
He means something like "outside of the scope of Java".
Specifically in Java the "correct" way to create a new object is by using that Object's constructor. Many class writers rely on this assumption and code logic into their constructors - things like input validation or anything else you want to guarantee at construction time - this is what he calls "invariants established by the constructors". But cloning bypasses this basic constraint and creates a memory copy without invoking the constructor - hence it is "extra linguistic".
Technically, so does serialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With