0

I'm reading J. Bloch's effective Java and now I'm at the clone method. He mentioned that no constructors were called. But I didn't find it in the javadoc. The second thing is that:

The provision that “no constructors are called” is too strong. A well-behaved clone method can call constructors to create objects internal to the clone under construction. If the class is final, clone can even return an object created by a constructor.

It seems a little contradictory to me. While he was mentioning that no constructors are called, he said that well-behaved clone can call constructors.

Couldn't you explain what he meant?

2 Answers 2

3

There are two different things:

  1. Your own implementation of clone() method in your own class which should follow some rules.
  2. An implementation of existing Object.clone() method.

I believe, when J. Bloch speaks about "no constructors were called", he assumes the behavior of existing Object.clone() method. But the quotation you cite is about your own implementation of clone() method which in some cases can construct new objects using constructor or even return such object.

Sign up to request clarification or add additional context in comments.

2 Comments

So where is the requirement for not calling the constructors?
I checked javadocs for JavaSE 5 and 6 and there was no such a quote. Where di he find it?
1

Classes implementing Cloneable interface can call clone() method from Object class without having CloneNotSupportedException. The signature of the clone() in Object class tells why constructors are not called if you call the inherited clone. It is native code, not pure Java.

protected native Object clone() throws CloneNotSupportedException;

And note that, this is just a shallow copy implementation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.