What is cloning and how to clone an object in java?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is cloning and how to clone an object in java??

26th Jun 2017, 12:42 AM
Santosh Kondepudi
Santosh Kondepudi - avatar
2 Answers
+ 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!"); } } }
26th Jun 2017, 3:16 AM
ChaoticDawg
ChaoticDawg - avatar
0
thankuu
26th Jun 2017, 3:25 AM
Santosh Kondepudi
Santosh Kondepudi - avatar