Object Clone in Java

Veröffentlicht am: 05 Januar 2022
auf dem Kanal: Yashwant Pathak
70
13

The object cloning is a way to create an exact copy of an object. For this purpose, the clone() method of an object class is used to clone an object. The Cloneable interface must be implemented by a class whose object clone is to create. If we do not implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed, so we can use object cloning.
ava keeps references of objects. If two reference are pointing to same object then modification to one reference will reflect in another reference as well. To prevent such situation, cloning is required. In cloning, a copy of object is to be created and used to that both objects can be modified independently. This is one of the major advantages of cloning.
public class EmployeeTest implements Cloneable {
int id;
String name = "";
Employee(int id, String name) {
this.id = id;
this.name = name;
}
public Employee clone() throws CloneNotSupportedException {
return (Employee)super.clone();
}
public static void main(String[] args) {
Employee emp = new Employee(115, "Raja");
System.out.println(emp.name);
try {
Employee emp1 = emp.clone();
System.out.println(emp1.name);
} catch(CloneNotSupportedException cnse) {
cnse.printStackTrace();
}
}
}
#java object#object clone in java


Auf dieser Seite können Sie das Online-Video Object Clone in Java mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Yashwant Pathak 05 Januar 2022 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 70 Mal angesehen und es wurde von 13 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!