0

Clone() is used for an exact copy of the object. like this

B s2=(B)s1.clone();  

But we can also copy object using syntax like #

B s2=s1;

in both scenario output is the same then why do we use clone()?

class B {
    int rollno;
    String name;

    B(int rollno,String name) {
        this.rollno = rollno;
        this.name = name;
    }
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    public static void main(String args[]) {
        try {
            B s1 = new B(101, "amit");

            B s2 = (B) s1.clone();

            System.out.println(s1.rollno + " " + s1.name);
            System.out.println(s2.rollno + " " + s2.name);
        } catch (CloneNotSupportedException c) {
        }
    }
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Rakesh
  • 45
  • 1
  • 9

3 Answers3

2

This line doesn't clone the object:

B s2=s1;

It simply creates a second variable s2 that references the same object.

You can see the difference when you try to modify s2 before printing either one:

B s1 = new B(101, "amit");

B s2 = s1;
s2.name="newName";

System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);

This code will print newName as the name for both lines, because there's really only one object referenced by two variables.

If you replace B s2 = s1 with B s2 = s1.clone() however, then it'll print two different names, because an actual copy of the object was created.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
0

Because when you write b1 = b2 you just create another reference to the same object.

B b1 = new B();    // b1 is a reference to the B object
B b2 = b1;         // b2 is a new reference to the same B object
B b3 = (B)b1.clone(); // b3 is a reference to the new B object (total two B objects in memory) 
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

s2 = s1 does not copy the object. It just points an additional variable at the same object.

If you then do s1.setFoo("bar") that will have affected "both" objects (because there is only one object).

Thilo
  • 257,207
  • 101
  • 511
  • 656