public class CopyByCloning implements Cloneable{ StringBuffer text;
public CopyByCloning(String text)
{
this.text=new StringBuffer(text);
}
public StringBuffer getText() {
return text;
}
public void setText(String text) {
this.text = new StringBuffer(text);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
CopyByCloning cbp1=new CopyByCloning("hello");
CopyByCloning cbp2=(CopyByCloning) cbp1.clone();
System.out.println("Before using setters");
System.out.println("Text from original one:"+cbp1.getText());
System.out.println("Text from cloned one:"+cbp2.getText());
cbp1.setText("bye");
System.out.println("\nAfter using setters");
System.out.println("Text from original one:"+cbp1.getText());
System.out.println("Text from cloned one:"+cbp2.getText());
} could someone explain why the output is Before using setters Text from original one: hello Text from cloned one: hello
After using setters Text from the original one: bye Text from cloned one: hello
thanks!