Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of copy does the default java.lang.Object.clone() method perform [closed]

Tags:

java

I am new to java can some one tell me please. Is it

Shallow copy: primitive types and references are copied

Deep copy: objects are copied recursively

There is no default implementation for clone()

like image 521
Simple-Solution Avatar asked Aug 07 '13 16:08

Simple-Solution


People also ask

What is clone () in Java?

Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Using Assignment Operator to create a copy of the reference variable.

What is default cloning in Java?

Shallow Cloning It is the default cloning process in Java where a shallow copy of the original object will be created with exact field. In case the original object has references to some other objects as fields, then only the references of that object will be cloned instead of new object creation.

Does Java clone do 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.

Why is the clone () method protected in Java Lang object?

The clone() is protected because it is not declared in the Cloneable interface. Because of this reason, the clone method becomes somewhat useless as it might make the copies of your existing data.


1 Answers

You can look at the documentation for clone():

The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.

like image 132
arshajii Avatar answered Oct 06 '22 00:10

arshajii