• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cloning and StringBuffering  RSS feed

 
Dennis Noren
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!