How does the Java cloning method work?

public class Student implements Cloneable { public Student clone() { Student clonedStudent = (Student) super.clone(); return clonedStudent; } } 

Why does Java return an object object instead of a return object of an object class. Since we use super. Does this mean that Java itself provides shallow cloning in the cloning method?

+7
source share
5 answers

java cloning field by field copy , i.e. since the Object class has no idea about the structure of the class on which the clone () method will be called.

1) If the class has only primitive members of the data type , then a completely new copy of the object will be created and a link to a copy of the new object will be returned.

2) If the class contains members of any type of class , then only references to objects for these members are copied and, therefore, references to both the original object and the cloned object, refer to the same object .

Send link cloning objects in java

+14
source

See what the docs say about this:

... Thus, this method performs a โ€œshallow copyโ€ of this object, and not a โ€œdeep copyโ€ operation.

Also see this link :

if the class has only primitive members of the data type, then a new copy of the object will be completely created and a copy of the object will be returned. But if the class contains members of any type of class, then only references to objects for these members are copied and, therefore, references to elements in the original object as a cloned object refers to the same object.

+9
source

clone() acts as a copy constructor.

Creates and returns a copy of the object. Since the Object class has a clone method (protected), you cannot use it in all your classes. The class you want to clone must implement the clone method and overwrite it. It should provide its value for copying, or at least should call super.clone() . You also need to implement the Cloneable marker interface, otherwise you will get a CloneNotSupportedException. When you call super.clone() , then you are dependent on the implementation of the object classes, and what you get is a shallow copy.

You can create a wiki page for a better understanding.

For the cloning object, you must implement the Cloneable interface

If you try to use the clone method in a class where the Cloneable interface is not implemented, it throws a CloneNotSupportedException .

+4
source

java.lang.Object provides a default implementation of the clone() method in Java. It is declared as protected and native in the Object class; therefore, it is implemented in native code. Since it is customary to return clone() object by calling the super.clone() method, any cloning process ultimately reaches the java.lang.Object clone() method. This method first checks to see if the corresponding object implements the Cloneable interface, which is the token interface. If this instance does not implement Cloneable, it CloneNotSupportedException a CloneNotSupportedException in the Java CloneNotSupportedException - a checked exception that must always be handled when cloning an object. In Java, if a class should support cloning, it should do the following things:

A) You must implement the Cloneable interface. B) You must override the clone() method from the Object class. [This is strange. the clone() method should have been in the Cloneable interface.]

The Java docs about the clone() method are given below (formatted and extracted) ./* Creates and returns a copy of this object. The exact meaning of "copy" may depend on the class of the object. The general intention is that for any object x expression: 1) x.clone() != x will be true // guarantees that the cloned object will have a separate memory address assignment. 2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements x.clone().getClass() == x.getClass() and the cloned objects must have the same same type of class, but this is not necessary. 3) x.clone().equals(x) will be true, this is not an absolute requirement of x.clone().equals(x) and the cloned objects should be equal when using the equals() method, but this is not necessary. * /

Let's see an example:

 public class MyClone { int x; public static void main(String[] args) throws CloneNotSupportedException { MyClone c = new MyClone(); MyClone a = (MyClone) c.clone(); // Type-cast is required } } 

Since clone() is part of the Object class, and Object will not implement the Cloneable interface when our own class does not implement the Cloneable interface, the JVM will not know that this class is suitable for cloning, so a CloneNotSupportedException .

When we say MyClone a = (MyClone) c.clone(); , only two things are possible. :

Or it will return the cloned object.

Or it will CloneNotSupportedException .

Since it is clear that it is not necessary to implement clone() in your class when you want to clone an object, if you do not, the clone() method in the Object class is declared protected - only subclasses and members of the same class will be able to call clone() for object. If you want to change this, you must override this and make it publicly available.

Checks before calling the clone() method:

 if(c instanceof Cloneable) { MyClone a = (MyClone) c.clone(); } 

Note: the constructor is not called when clone() called. Our responsibility is to correctly set all member variables of this class.

Implementation:

 Room.java public class Room { private String roomSize; public Room(String roomSize){ this.roomSize = roomSize; } //Any Getters-Setters go here } Flat.java public class Flat implements Cloneable { private String flatNumber; private Room room; public Flat(String size,Room room){ this.size = size; this.room = room; } public Object clone() { try { return (Flat)super.clone(); } catch (CloneNotSupportedException e) { System.out.println("CloneNotSupportedException comes out : " +e.getMessage()); } } //Any Getters-Setters go here } Main.java public class Main { public static void main(String[] args) { Room room = new Room("40 X 40"); Flat flat1 = new Flat(403 , room); Flat flat2 = (Flat)flat1.clone(); } } 

Here super.clone() is called inside clone() . As we know, clone() declared in Object , so it is inherited by every Java object. Calling super.clone() copies the fields of our superclass and makes bitwise copies of the fields. This is called shallow copying, which means that when copying Flat using clone() the flatNumber field flatNumber copied with the corresponding values, but the space is copied by reference - bit by bit, the memory address is copied.

Any changes made to the room of the original object will be reflected in the cloned object and vice versa. To solve this, we need a deep copy. Now we need to change the Room class and implement the Cloneable interface and the clone() method, and then call the clone() method of the Room object inside the clone() method of the Flat object.

New implementation

 Room.java public class Room { private String roomSize; public Room(String roomSize){ this.roomSize = roomSize; } public Object clone() { try { return (Room)super.clone(); } catch (CloneNotSupportedException e) { System.out.println("CloneNotSupportedException comes out : " +e.getMessage()); } } //Any Getters-Setters go here } Flat.java public class Flat implements Cloneable { private String flatNumber; private Room room; public Flat(String size,Room room){ this.size = size; this.room = room; } public Object clone() { Flat flat = null; try { flat = (Flat)super.clone(); } catch (CloneNotSupportedException e) { System.out.println("CloneNotSupportedException comes out : " +e.getMessage()); } flat.room = (Room) room.clone(); return flat; } //Any Getters-Setters go here } Main.java public class Main { public static void main(String[] args) { Room room = new Room("40 X 40"); Flat flat1 = new Flat(403, room); Flat flat2 = (Flat)flat1.clone(); } } 

I hope this gives a better understanding of cloning and its implementation.

Thanks http://interviewguess.blogspot.in/2017/02/how-does-clone-method-work.html

+1
source

According to String, javadoc clone() from Object generates a shallow copy of the object it is calling from.

If you implement clone() , the convention is that you get the original copy from super.clone() , and then do the rest of the clone operation, modifying this returned object.

0
source

Source: https://habr.com/ru/post/1493803/


All Articles