Forums Register Login

Cloning and StringBuffering

+Pie Number of slices to send: Send
I can make StringBuffer a verb, can't I?

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?
+Pie Number of slices to send: Send
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!
When it is used for evil, then watch out! When it is used for good, then things are much nicer. Like this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 943 times.
Similar Threads
How to fix error in Rectangle Class problem in Java?
This must be embarrassingly simple
Drawing text inside a Graphics2D shape
Why does this get a run-time error?
Overriding equals()
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:11:15.