Waqar Ul Khaf Waqar Ul Khaf - 1 month ago 15
Java Question

Prototype Creation Pattern

In java we have and interface cloneable What I want to understand is why abstract class implements that interface there is still no implementation of clone() method of interface in abstract class ?

Answer

In java we have and interface cloneable What I want to understand is why abstract class implements that interface there is still no implementation of clone() method of interface in abstract class ?

Object class provides default implementation for Object's methods whose clone() method.

When you look Object class, you can see that clone() specifies a particular keyword in its signature : native.

protected native Object clone() throws CloneNotSupportedException;

The native keyword is applied to a method to indicate that it is implemented in JNI(Java Native Interface).
So, the implementation exists somewhere (probably in a C function but not exclusively...) but not directly in the Java source code of the method.

Finally, you should consider the Cloneable interface as what it stands for : a marker interface. If you want that you object to be cloneable, implement this and if you don't care, do nothing :

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

Now, if default implementation of clone() method (shallow copy) doesn't match with how do you want to clone your object, feel free to override clone() in the class of this object.

Comments