Monday, September 30, 2013

How clone method works in Java

clone is a tricky method from java.lang.Object class, which is used to create copy of an Object in Java. Intention of clone() method is simple, to provide a cloning mechanism, but some how it's implementation became tricky and has been widely criticized from long time. Anyway, we will not go to classic debate of clone in Java, at-least for now; instead, we will try to learn how clone method works in Java. To be fair, understating cloning mechanism in Java is not easy and even experienced Java programmer fail to explain how cloning of mutable object works, or difference between deep copy and shallow copy in Java. In this three part article, we will first see working of clone method in Java, and in second part we will learn how to override clone method in Java, and finally we will discuss deep copy vs shallow copy mechanism. The reason I chose to make this a three part article, is to keep focus on one thing at a time. Since clone() itself is confusing enough, it's best to understand concept one by one. In this post, we will learn what is clone method, what it does and How 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.
Read more �

No comments:

Post a Comment