1

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!

kiki
  • 62
  • 5

1 Answers1

0

The output of your program is:

Before using setters
Text from original one:hello
Text from cloned one:hello

After using setters
Text from original one:bye
Text from cloned one:hello

This is because you use a "clone" of the first object to create the second object:

    CopyByCloning cbp2=(CopyByCloning) cbp1.clone();

This is called a deep copy, and it means that a new object is created in memory, and is initialized with the values of the first object. Therefore, one change in the object will not affect the other

This is opposed to a shallow copy, which means that no new object is created, but the address which points to the object in memory is copied to the second object. This means that every time you modify the object, the changes will also be reflected in the other object.

For example, if you write the second object this way:

    CopyByCloning cbp2=(CopyByCloning) cbp1;

The output will be the following:

Before using setters
Text from original one:hello
Text from cloned one:hello

After using setters
Text from original one:bye
Text from cloned one:bye

For more information, you can read: What is the difference between a deep copy and a shallow copy?

CanciuCostin
  • 1,773
  • 1
  • 10
  • 25