I am implementing a cloneable interface, and it mostly seems to work correctly, except for the following.
I have a class Shape, with data elements Color color; StringBuffer description;
The clones seem to work correctly, except that when I try to run my setDesc method to change the description on the clone, it changes the description on the original also. My setColor method does not show the same behavior.
Here is my clone override method (there is also a rectangle subclass):
and here is my equals override method:
I create and clone as follows:
And then I print shape3 and shape4, and they both have the new text in the description data member. Any idea why this is happening?
Java novice, J2SE 1.4.2<br />Some C, some OOA/OOD
author and iconoclast
The default implementation of clone() (the one you get by calling super.clone()) does a "shallow copy" -- the reference variables in the object are copied, but not the objects they point to. This means that after you call clone(), both the old and new Shape objects share the same StringBuffer object to hold their description, which obviously gives you the problem you're observing.
Solution: do the same thing with description that you do with rect!