Sponsored Link •
Bill Venners: In The Java Programming
Language, you discuss
clone and suggest how to use it. You have
said to me previously that you think
clone is broken.
Ken Arnold: I think
clone is a real mess.
Bill Venners: But given
clone's current state,
how would you recommend people use it? What do you think of Bloch's suggestion in
Effective Java to create copy constructors rather than using the
Ken Arnold: The problem with a copy constructor is that you have
to know the type of thing you're cloning or copying. You have to make a
Foo given an old
Foo that is passed into the copy
constructor. But if the object the client holds is not a
Foo, but is a
Foo subtype, then you could end up doing type truncation, which you
don't want to do.
Bill Venners: What do you mean by type truncation?
Ken Arnold: Suppose you have a
Foo, which has a
Bar. If you ask
Foo to clone itself and you have a
Foo will do all the
But if you use this copy constructor mechanism and you tell
Foo to create
Foo and pass in the old
Bar, you will get a new
Foo instead of a
Bar. You lose the bottom of the type.
Bill Venners: You're fubar.
Ken Arnold: You're definitely fubar. So using a copy constructor implies a mechanism where you ask the passed object its type. You get its class object, and invoke its copy constructor by reflection. When you do that, you are way into ugliness.
If I were to be God at this point, and many people are probably glad I am not, I would
Cloneable and have a
Cloneable has problems. Besides the fact that it's misspelled,
Cloneable doesn't contain the
clone method. That means
you can't test if something is an instance of
Cloneable, cast it to
Cloneable, and invoke
clone. You have to use reflection
again, which is awful. That is only one problem, but one I'd certainly solve.