|
|
|
|
It turns out that the Object class's clone() method refuses to work if your class doesn't implement the Cloneable interface. What's the Cloneable interface? Java provides an interface Cloneable, in the package java.lang. Here is the code that defines it (with comments removed):
That is everything you need to know about interface Cloneable! Notice that it is a marker interface, because it contains absolutely no methods, nor anything else. The idea is that you can only call the Object class's clone() method if your class implements this interface. So let's do that:
Now, this compiles, and when you test it:
it produces the following output: ---CloneMe object--- Object: HashId: MyObject@923e30 Name: Monkeys Value: 27 ---CloneMe object--- Object: HashId: MyObject@923e30 Name: Monkeys Value: 27We've finally succeeded in cloning the object! So we're done, right? Nope! Take a look at the output more carefully. While we actually have two distinct object instances of type CloneMe, each of those instances contain an Object reference which points to a single instance of MyObject. That's what I meant by the Object class's clone() method doing a shallow copy. It copied the reference, not what the reference referred to. Depending on what our class is designed to do, this may be appropriate, or it may be completely wrong. Under what circumstances can you think of where it might be incorrect? |
|
This page was last modified on 02 October, 2007 |