Object Cloning in Java
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class. Syntax of the clone() method is as follows: Why use clone() method ?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 time to be performed that is why we use object cloning. Advantage of Object cloningAlthough Object.clone() has some design issues but it is still a popular and easy way of copying objects. Following is a list of advantages of using clone() method:
Disadvantage of Object cloningFollowing is a list of some disadvantages of clone() method:
Example of clone() method (Object cloning)Let’s see the simple example of object cloning Output:101 amit 101 amit As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don’t need to write explicit code to copy the value of an object to another. If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263814.html