Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

Probably the fact that it isn't implemented in Java but it has a native in the Object class.

The extra-linguistic object creation mechanisms (meaning other than calling or chaining constructors) are:

  1. cloning
  2. serialization
  3. reflection
  4. btye-code generation
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top