How does clone() method works in Java?
Exploring Java's clone() method to answer difference between deep cloning and shallow cloning
Hello folks, the clone()
is a tricky method from java.lang.Object
class, which is used to create a copy of an object in Java. The intention of the clone()
method is simple, to provide a cloning mechanism, but somehow its implementation became tricky and has been widely criticized for a long time.
Anyway, we will not go to the classic debate of clones in Java, at least for now; instead, we will try to learn how the clone method works in Java.
To be fair, understating the cloning mechanism in Java is not easy and even experienced Java programmers fail to explain how cloning of mutable objects works, or the difference between deep and shallow copy in Java.
In this three-part article, we will first see the working of the clone method in Java, and in the second part we will learn how to override the clone method in Java, and finally, we will discuss the deep copy vs shallow copy mechanism.
The reason I chose to make this a three-part article is to keep the focus on one thing at a time.
Since clone() itself is confusing enough, it's best to understand concepts one by one. In this post, we will learn what is clone method is, what it does, and How the clone method works in Java.
By the way, clone()
is one of the few fundamental methods defined by objects, others being equals, hashcode(), toString()
along with wait and notify methods.
Keep reading with a 7-day free trial
Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.