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) {
}
}
}