Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Java clone method work?

Tags:

java

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?

like image 304
Ullas Avatar asked Jul 27 '13 12:07

Ullas


People also ask

How the clone () method works in Java?

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().

How does clone function work?

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 .

Does clone method return object?

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.

Is Java clone a deep copy?

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.


1 Answers

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

like image 140
bNd Avatar answered Sep 21 '22 05:09

bNd