Object.clone() throwing exception on a call on a Object type instance - why?
If we try to call the Object.clone() method on an instance of type Object, then it throws CloneNotSupportedException. Looks strange, isn't it? After all clone() is a method of the Object class only, so what's the problem when a call to this method is being made on an instance of Object type. Well... the problem is that Object.clone() method can only be called on an instance of a class if that class implements the marker interface named Cloneable and the cosmic super class Object doesn't implement this interface :-)
If we want to use the clone() method then we simply need to implement this interface and we'll instantly get the license to use the default cloning functionality which is a simple field-by-field copy of the members. Read more about clong in this article - Cloning in Java - How it works?
Friday, June 13, 2008
Object.clone() throwing exception for an Object instance
Subscribe to:
Post Comments (Atom)
1 comment:
Good pick. I've read Cloning in Java many times, but it didn't cross my mind :-)
Post a Comment