0
What is cloning and how to clone an object in java??
2 Respostas
+ 1
Cloning is making an exact copy of an object in java. In order to be able to clone an object it must implement the cloneable interface.
import java.lang.Cloneable;
public class MyObject implements Cloneable {
private String str;
private int myInt;
public void setStr(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setInt(int myInt) {
this.myInt = myInt;
}
public int getInt() {
return myInt;
}
public Object clone()throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) {
MyObject obj1 = new MyObject();
obj1.setStr("hello");
obj1.setInt(42);
System.out.println("obj1: " + obj1.getStr()
+ " " + obj1.getInt());
try {
MyObject obj2 = (MyObject)obj1.clone();
System.out.println("obj2: " + obj2.getStr()
+ " " + obj2.getInt());
} catch (CloneNotSupportedException e) {
System.out.println("Unable to clone!");
}
}
}
0
thankuu