Interview Questions

What is The clone() method?

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

What is The clone() method?

In Java, the way to make an identical copy of an object is to invoke clone() on that object. When you invoke clone(), it should either:

1. return an Object reference to a copy of the object upon which it is invoked, or
2. throw CloneNotSupportedException

Because clone() is declared in class Object, it is inherited by every Java object. Object's implementation of clone() does one of two things, depending upon whether or not the object implements the Cloneable interface. If the object doesn't implement the Cloneable interface, Object's implementation of clone() throws a CloneNotSupportedException. Otherwise, it creates a new instance of the object, with all the fields initialized to values identical to the object being cloned, and returns a reference to the new object.

The Cloneable interface doesn't have any members. It is an empty interface, used only to indicate cloning is supported by a class. Class Object doesn't implement Cloneable. To enable cloning on a class of objects, the class of the object itself, or one of its superclasses other than Object, must implement the Cloneable interface.

In class Object, the clone() method is declared protected. If all you do is implement Cloneable, only subclasses and members of the same package will be able to invoke clone() on the object. To enable any class in any package to access the clone() method, you'll have to override it and declare it public, as is done below. (When you override a method, you can make it less private, but not more private. Here, the protected clone() method in Object is being overridden as a public method.)

(Continued on next question...)

Other Interview Questions