Monday, June 16, 2008

What's the potential problem with overriding clone() method?


Question: What's the potential problem with overriding clone() method?

Answer: clone() method has 'protected' access in the class java.lang.Object and we normally override this method and promote the access to 'public' for the overriden method. We do this even in the case we are interested in using the default cloning (Shallow Copy) functionality only; otherwise we'll get a compile time error if we try to call this method from outside. Read more about this in this article - clone() not accessible from outside >>

Potential problem with this access promotion

This 'protected' to 'public' access promotion will ensure that all the subclasses of this class will inherit this 'public' clone() method even though they may not need it (and hence they will not bother about overriding the inherited clone() method for its suitability in the particular sub class). If these subclasses (or their subclasses, and so on) don't add any non-primitive member then it'll hardly affect us otherwise the usage of the inherited clone() method on that subclass instance will result in Shallow Copy even if the original clone() was written for implementing Deep Copy. Read more - Shallow Copy vs Deep Copy >>



Share/Save/Bookmark


No comments: