Difference between shallow cloning and deep cloning of objects in Java

What is the main difference between shallow cloning and deep cloning of objects?

Shallow cloning just allows cloning the object but not their internal parts.

For example, an address book contains street and city. To clone an address book, add the references to the street and city names.

Deep cloning clones the objects as well as their parts.

For example, a car HAS four wheels. To clone a car, four wheels must be cloned.

That distinction is a little difficult to be done in Java, but is better understood if you think in terms of databases.

You need deep cloning if the entity requires "cascade deleting" to be deleted. You need shallow cloning if "cascade deleting" is not needed.

What is the main difference between shallow cloning and deep cloning of objects?

When an object is shallow copied, the copy simply points to the same location the previous object points to. Due to this, the change made to the values by referring the initial object would also reflect when the object is retrieved using the copied reference.

When an object is deep copied, the values too are copied, due to which separate references are maintained and a change in the initial object does not affect the values in the copy.
What is the difference between final, finally and finalize() in Java?
Final, finally and finalize() in Java - final – a key word / access modifier to define constants......
What is type casting? Explain up casting vs down casting?
The conversion of a given expression from one type to another type is referred as 'type casting'...
Different types of inner classes in Java
There are 4 types of inner classes - Member inner class, Local inner class, Static inner class and Anonymous inner class...
Post your comment