The trap in clone
To my horror, I found out today that I’d missed something basic about how to override clone(). I’d say even the best carpenters sometimes slip, except I hardly think of myself as one of the best. Let’s see where the problem lies.
public class A implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return new A();
}
}public class B extends A implements Cloneable {
@Override
protected Object clone() throws CloneNotSupportedException {
return (B) super.clone();
}
}The problem is in the overridden clone method of class A, which fails to use the superclass’s clone method (java.lang.Object#clone). The java.lang.Object method guarantees that the result is a copy of the very object it was called on.
Here’s the correct version.
@Override
protected Object clone() throws CloneNotSupportedException {
Object clone = super.clone();
assert clone instanceof A;
return clone;
}If we fail to follow this convention in every class, we’ll get a ClassCastException. Good to know! I’m almost embarrassed to tag this post “for beginners.”
Related articles
Related CZ Podcast episodes
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio