public class Student implements Cloneable {
public Student clone() {
Student clonedStudent = (Student) super.clone();
return clonedStudent;
}
}
Why does Java return student object instead of returning object class object. As we are using super. Does it mean Java itself provides shallow cloning in the clone method?
The clone method creates an exact copy of an object for which it has been invoked in a field-by-field assignment order and will return the new object reference. One thing that you must remember, in Java, the objects which implement the clone interface which is a marker interface is allowed to use the clone().
The class Object 's clone() method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, Object. clone() throws a CloneNotSupportedException unless the object is an instance of a class that implements the marker interface Cloneable .
Cloning is the process of creating a copy of an Object. Java Object class comes with native clone() method that returns the copy of the existing instance. Since Object is the base class in Java, all objects by default support cloning.
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
java cloning is field by field copy
i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked.
1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.
2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.
Refer this link object cloning in java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With